author
int64 658
755k
| date
stringlengths 19
19
| timezone
int64 -46,800
43.2k
| hash
stringlengths 40
40
| message
stringlengths 5
490
| mods
list | language
stringclasses 20
values | license
stringclasses 3
values | repo
stringlengths 5
68
| original_message
stringlengths 12
491
|
---|---|---|---|---|---|---|---|---|---|
455,741 | 19.09.2022 16:15:54 | 25,200 | a46fd29bf1d14230dcb4da234fccc03732538453 | support more language for syntax highlighting | [
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/App_Code/ViewHelpers.cshtml",
"new_path": "src/NuGetGallery/App_Code/ViewHelpers.cshtml",
"diff": "@@ -735,6 +735,9 @@ var hlp = new AccordionHelper(name, formModelStatePrefix, expanded, page);\n@helper IncludeSyntaxHighlightScript()\n{\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/styles/github.min.css\" integrity=\"sha512-0aPQyyeZrWj9sCA46UlmWgKOP0mUipLQ6OZXu8l4IcAmD2u31EPEy9VcIMvl7SoAaKe8bLXZhYoMaE/in+gcgA==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\" />\n- @* highlight.js build includes support for:: bash, c, cpp, csharp, css, diff, go, ini, java, json, javascript, kotlin, less, lua, makefile, xml, markdown, perl, php, objectivec, plaintext, python, r, ruby,rust, scss, shell, sql, swift, vbnet, yaml*@\n+ @* highlight.js build includes support for:: bash, c, cpp, csharp, css, diff, go, ini, java, json, javascript, typescript, kotlin, less, lua, makefile, xml, markdown, perl, php, objectivec, plaintext, python, r, ruby,rust, scss, shell, sql, swift, vbnet, yaml, html, fsharp, powershell, dos*@\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/highlight.min.js\" integrity=\"sha512-gU7kztaQEl7SHJyraPfZLQCNnrKdaQi5ndOyt4L4UPL/FHDd/uB9Je6KDARIqwnNNE27hnqoWLBq+Kpe4iHfeQ==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\"></script>\n+ <script src=\"https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/languages/fsharp.min.js\" integrity=\"sha512-DXYctkkhmMYJ4vYp4Dm6jprD4ZareZ7ud/d9mGCKif/Dt3FnN95SjogHvwKvxXHoMAAkZX6EO6ePwpDIR1Y8jw==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\"></script>\n+ <script src=\"https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/languages/dos.min.js\" integrity=\"sha512-mz4SrGyk+dtPY9MNYOMkD81gp8ajViZ4S0VDuM/Zqg40cg9xgIBYSiL5fN79Htbz4f2+uR9lrDO6mgcjM+NAXA==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\"></script>\n+ <script src=\"https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/languages/powershell.min.js\" integrity=\"sha512-pnt8OPBTOklRd4/iSW7msOiCVO4uvffF17Egr3c7AaN0h3qFnSu7L6UmdZJUCednMhhruTLRq7X9WbyAWNBegw==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\"></script>\n}\n\\ No newline at end of file\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | support more language for syntax highlighting (#9232) |
455,784 | 22.09.2022 10:56:52 | 25,200 | 7ee48b30285551cef9f38fbcb044cf56669f405e | add hidden warning label | [
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/ViewModels/ThirdPartyPackageManagerViewModel.cs",
"new_path": "src/NuGetGallery/ViewModels/ThirdPartyPackageManagerViewModel.cs",
"diff": "@@ -19,7 +19,7 @@ public ThirdPartyPackageManagerViewModel(string name, string contactUrl) : base(\n{\nContactUrl = contactUrl;\nAlertLevel = AlertLevel.Warning;\n- AlertMessage = \"The NuGet Team does not provide support for this client. Please contact its \"\n+ AlertMessage = \"<b display=\\\"none\\\" aria-label=\\\"warning\\\"></b> The NuGet Team does not provide support for this client. Please contact its \"\n+ $\"<a href=\\\"{contactUrl}\\\" aria-label=\\\"Contact the maintainers of the {name} client\\\">maintainers</a> for support.\";\n}\n}\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | add hidden warning label (#9247) |
455,736 | 27.09.2022 06:25:22 | 25,200 | aa802046369fd17688cfa0e1eca81e7599bcd6c7 | Update to ServerCommon 2.106.0 to resolve CG alerts | [
{
"change_type": "MODIFY",
"old_path": "src/DatabaseMigrationTools/DatabaseMigrationTools.csproj",
"new_path": "src/DatabaseMigrationTools/DatabaseMigrationTools.csproj",
"diff": "<PrivateAssets>all</PrivateAssets>\n</PackageReference>\n<PackageReference Include=\"NuGet.Services.Validation\">\n- <Version>2.105.0</Version>\n+ <Version>2.106.0</Version>\n</PackageReference>\n</ItemGroup>\n<ItemGroup>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/GitHubVulnerabilities2Db/GitHubVulnerabilities2Db.csproj",
"new_path": "src/GitHubVulnerabilities2Db/GitHubVulnerabilities2Db.csproj",
"diff": "<Version>4.3.0-dev-5590084</Version>\n</PackageReference>\n<PackageReference Include=\"NuGet.Services.Cursor\">\n- <Version>2.105.0</Version>\n+ <Version>2.106.0</Version>\n</PackageReference>\n</ItemGroup>\n<ItemGroup>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery.Core/NuGetGallery.Core.csproj",
"new_path": "src/NuGetGallery.Core/NuGetGallery.Core.csproj",
"diff": "<Version>6.0.0</Version>\n</PackageReference>\n<PackageReference Include=\"NuGet.Services.FeatureFlags\">\n- <Version>2.105.0</Version>\n+ <Version>2.106.0</Version>\n</PackageReference>\n<PackageReference Include=\"WindowsAzure.Storage\">\n<Version>9.3.3</Version>\n<ItemGroup Condition=\"'$(TargetFramework)' == 'net472'\">\n<PackageReference Include=\"NuGet.Services.Messaging.Email\">\n- <Version>2.105.0</Version>\n+ <Version>2.106.0</Version>\n</PackageReference>\n<PackageReference Include=\"NuGet.Services.Validation\">\n- <Version>2.105.0</Version>\n+ <Version>2.106.0</Version>\n</PackageReference>\n<PackageReference Include=\"NuGet.Services.Validation.Issues\">\n- <Version>2.105.0</Version>\n+ <Version>2.106.0</Version>\n</PackageReference>\n<PackageReference Include=\"NuGet.StrongName.elmah.corelibrary\">\n<Version>1.2.2</Version>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery.Services/NuGetGallery.Services.csproj",
"new_path": "src/NuGetGallery.Services/NuGetGallery.Services.csproj",
"diff": "<Version>6.0.0</Version>\n</PackageReference>\n<PackageReference Include=\"NuGet.Services.Configuration\">\n- <Version>2.105.0</Version>\n+ <Version>2.106.0</Version>\n</PackageReference>\n<PackageReference Include=\"NuGet.Services.Logging\">\n- <Version>2.105.0</Version>\n+ <Version>2.106.0</Version>\n</PackageReference>\n<PackageReference Include=\"NuGet.StrongName.WebBackgrounder\">\n<Version>0.2.0</Version>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/NuGetGallery.csproj",
"new_path": "src/NuGetGallery/NuGetGallery.csproj",
"diff": "<Version>1.4.0</Version>\n</PackageReference>\n<PackageReference Include=\"NuGet.Services.Licenses\">\n- <Version>2.105.0</Version>\n+ <Version>2.106.0</Version>\n</PackageReference>\n<PackageReference Include=\"NuGet.Services.Owin\">\n- <Version>2.105.0</Version>\n+ <Version>2.106.0</Version>\n</PackageReference>\n<PackageReference Include=\"NuGet.Services.Sql\">\n- <Version>2.105.0</Version>\n+ <Version>2.106.0</Version>\n</PackageReference>\n<PackageReference Include=\"Owin\">\n<Version>1.0.0</Version>\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | Update to ServerCommon 2.106.0 to resolve CG alerts (#9254) |
455,736 | 27.09.2022 17:33:11 | 25,200 | 6ebbcd0597823b86478067918260de913cfeba61 | Add missing binding redirect for Microsoft.Owin | [
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Web.config",
"new_path": "src/NuGetGallery/Web.config",
"diff": "</dependentAssembly>\n<dependentAssembly>\n<assemblyIdentity name=\"Microsoft.Owin\" publicKeyToken=\"31BF3856AD364E35\" culture=\"neutral\"/>\n- <bindingRedirect oldVersion=\"0.0.0.0-4.1.1.0\" newVersion=\"4.1.1.0\"/>\n+ <bindingRedirect oldVersion=\"0.0.0.0-4.2.2.0\" newVersion=\"4.2.2.0\"/>\n</dependentAssembly>\n<dependentAssembly>\n<assemblyIdentity name=\"System.Net.Http.Primitives\" publicKeyToken=\"B03F5F7F11D50A3A\" culture=\"neutral\"/>\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | Add missing binding redirect for Microsoft.Owin (#9256) |
455,736 | 04.10.2022 09:39:46 | 25,200 | 340527635aac79cea965b6e3daebd376f682d459 | Address three CodeQL errors
First, ignore moment.js issues by classifying it as a library.
Second, resolve an escaping issue by using a built-in jQuery method.
Third, surpress a usage of MD5 for backwards compatibility reasons. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "CodeQL.yml",
"diff": "+path_classifiers:\n+ library:\n+ # The default behavior is to tag library code as `library`. Results are hidden\n+ # for library code. You can tag further files as being library code by adding them\n+ # to the `library` section.\n+ - \"src/NuGetGallery/Scripts/gallery/moment-*.js\"\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Scripts/gallery/autocomplete.js",
"new_path": "src/NuGetGallery/Scripts/gallery/autocomplete.js",
"diff": "}\nfunction jquerySafeId(id) {\n- return id.replace(/\\./g, \"\\\\.\");\n+ return jQuery.escapeSelector(id);\n}\nfunction safeId(id) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Services/CertificateService.cs",
"new_path": "src/NuGetGallery/Services/CertificateService.cs",
"diff": "@@ -60,6 +60,7 @@ public async Task<Certificate> AddCertificateAsync(HttpPostedFileBase file)\ncertificate = new Certificate()\n{\n#pragma warning disable CS0618 // Only set the SHA1 thumbprint, for backwards compatibility. Never read it.\n+ // CodeQL [SM02196] Only set the SHA1 thumbprint, for backwards compatibility. Never read it.\nSha1Thumbprint = certificateFile.Sha1Thumbprint,\n#pragma warning restore CS0618\nThumbprint = certificateFile.Sha256Thumbprint,\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | Address three CodeQL errors (#9260)
First, ignore moment.js issues by classifying it as a library.
Second, resolve an escaping issue by using a built-in jQuery method.
Third, surpress a usage of MD5 for backwards compatibility reasons. |
455,736 | 06.10.2022 11:22:52 | 25,200 | 44336f1a702de438979ed9a74b96962b06230548 | Update NuGetGallery.Services to address CG alerts | [
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery.Services/NuGetGallery.Services.csproj",
"new_path": "src/NuGetGallery.Services/NuGetGallery.Services.csproj",
"diff": "<Version>1.0.0</Version>\n</PackageReference>\n<PackageReference Include=\"Microsoft.Owin\">\n- <Version>4.1.0</Version>\n+ <Version>4.2.2</Version>\n</PackageReference>\n<PackageReference Include=\"Microsoft.Owin.Host.SystemWeb\">\n- <Version>4.1.0</Version>\n+ <Version>4.2.2</Version>\n</PackageReference>\n<PackageReference Include=\"Microsoft.Owin.Security\">\n- <Version>4.1.0</Version>\n+ <Version>4.2.2</Version>\n</PackageReference>\n<PackageReference Include=\"Microsoft.Owin.Security.Cookies\">\n- <Version>4.1.0</Version>\n+ <Version>4.2.2</Version>\n</PackageReference>\n<PackageReference Include=\"Microsoft.Owin.Security.MicrosoftAccount\">\n- <Version>4.1.0</Version>\n+ <Version>4.2.2</Version>\n</PackageReference>\n<PackageReference Include=\"Microsoft.Owin.Security.OpenIdConnect\">\n- <Version>4.1.0</Version>\n+ <Version>4.2.2</Version>\n</PackageReference>\n<PackageReference Include=\"NuGet.Protocol\">\n<Version>6.0.0</Version>\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | Update NuGetGallery.Services to address CG alerts (#9274) |
455,769 | 12.10.2022 22:57:34 | -3,600 | 48dde8ef917ffeaf9defa67a9fb411ab51139ee1 | Add instructions to install MSBuildSdk packages
* Added "IsMSBuildSdkPackageType" to determine whether a package is of type MSBuildSdk.
DisplayPackage view modified to show specific instructions for SDK types in project files as per
* Changed "Include" to correct attribute "Name" for SDK package type | [
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Helpers/ViewModelExtensions/DisplayPackageViewModelFactory.cs",
"new_path": "src/NuGetGallery/Helpers/ViewModelExtensions/DisplayPackageViewModelFactory.cs",
"diff": "@@ -104,6 +104,7 @@ public DisplayPackageViewModelFactory(IIconUrlProvider iconUrlProvider)\n// Lazily load the package types from the database.\nviewModel.IsDotnetToolPackageType = package.PackageTypes.Any(e => e.Name.Equals(\"DotnetTool\", StringComparison.OrdinalIgnoreCase));\nviewModel.IsDotnetNewTemplatePackageType = package.PackageTypes.Any(e => e.Name.Equals(\"Template\", StringComparison.OrdinalIgnoreCase));\n+ viewModel.IsMSBuildSdkPackageType = package.PackageTypes.Any(e => e.Name.Equals(\"MSBuildSdk\", StringComparison.OrdinalIgnoreCase));\n}\nif (packageKeyToDeprecation != null && packageKeyToDeprecation.TryGetValue(package.Key, out var deprecation))\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/ViewModels/DisplayPackageViewModel.cs",
"new_path": "src/NuGetGallery/ViewModels/DisplayPackageViewModel.cs",
"diff": "@@ -33,6 +33,7 @@ public class DisplayPackageViewModel : ListPackageItemViewModel\npublic bool IsDotnetToolPackageType { get; set; }\npublic bool IsDotnetNewTemplatePackageType { get; set; }\n+ public bool IsMSBuildSdkPackageType { get; set; }\npublic bool IsAtomFeedEnabled { get; set; }\npublic bool IsPackageDeprecationEnabled { get; set; }\npublic bool IsPackageVulnerabilitiesEnabled { get; set; }\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Views/Packages/DisplayPackage.cshtml",
"new_path": "src/NuGetGallery/Views/Packages/DisplayPackage.cshtml",
"diff": "}\n};\n}\n+ else if (Model.IsMSBuildSdkPackageType)\n+ {\n+ packageManagers = new PackageManagerViewModel[]\n+ {\n+ new PackageManagerViewModel(\"SDK\")\n+ {\n+ Id = \"sdk\",\n+ InstallPackageCommands = new [] { string.Format(\"<Sdk Name=\\\"{0}\\\" Version=\\\"{1}\\\" />\",\n+ Model.Id, Model.Version) },\n+ AlertLevel = AlertLevel.Info,\n+ AlertMessage = string.Format(\"For projects that support Sdk, copy this XML node into the project file to reference the package.\"),\n+ CopyLabel = \"Copy the SDK XML node\",\n+ }\n+ };\n+ }\nelse\n{\npackageManagers = new PackageManagerViewModel[]\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | Add instructions to install MSBuildSdk packages (#9268)
* Added "IsMSBuildSdkPackageType" to determine whether a package is of type MSBuildSdk.
DisplayPackage view modified to show specific instructions for SDK types in project files as per #8800
* Changed "Include" to correct attribute "Name" for SDK package type
Co-authored-by: Advay Tandon <[email protected]>
Co-authored-by: lyndaidaii <[email protected]> |
455,736 | 19.10.2022 16:16:10 | 25,200 | 61e016974cae06783e7253d1d450483511901172 | Fix bug around handling security advisories with 100 or more affected packages
The original implementation used a securityAdvisory(databaseId) query which no longer exists. This switches to using GHSA ID as the parameter. | [
{
"change_type": "MODIFY",
"old_path": "src/GitHubVulnerabilities2Db/Collector/AdvisoryQueryBuilder.cs",
"new_path": "src/GitHubVulnerabilities2Db/Collector/AdvisoryQueryBuilder.cs",
"diff": "using System;\nusing System.Linq;\nusing GitHubVulnerabilities2Db.GraphQL;\n+using Newtonsoft.Json;\nnamespace GitHubVulnerabilities2Db.Collector\n{\npublic class AdvisoryQueryBuilder : IAdvisoryQueryBuilder\n{\n+ private const string SecurityAdvisoryFields = @\"databaseId\n+ ghsaId\n+ permalink\n+ severity\n+ withdrawnAt\n+ updatedAt\";\n+\npublic int GetMaximumResultsPerRequest() => 100;\npublic string CreateSecurityAdvisoriesQuery(DateTimeOffset? updatedSince = null, string afterCursor = null)\n@@ -20,27 +28,21 @@ public string CreateSecurityAdvisoriesQuery(DateTimeOffset? updatedSince = null,\nedges {\ncursor\nnode {\n- databaseId\n- permalink\n- severity\n- withdrawnAt\n- updatedAt\n+ \" + SecurityAdvisoryFields + @\"\n\" + CreateVulnerabilitiesConnectionQuery() + @\"\n}\n}\n}\n}\";\n+ /// <summary>\n+ /// Source: https://docs.github.com/en/enterprise-cloud@latest/graphql/reference/queries#securityadvisory\n+ /// </summary>\npublic string CreateSecurityAdvisoryQuery(SecurityAdvisory advisory)\n=> @\"\n{\n- securityAdvisory(databaseId: \" + advisory.DatabaseId + @\") {\n- severity\n- updatedAt\n- identifiers {\n- type\n- value\n- }\n+ securityAdvisory(ghsaId: \" + JsonConvert.SerializeObject(advisory.GhsaId) + @\") {\n+ \" + SecurityAdvisoryFields + @\"\n\" + CreateVulnerabilitiesConnectionQuery(advisory.Vulnerabilities?.Edges?.Last()?.Cursor) + @\"\n}\n}\";\n"
},
{
"change_type": "MODIFY",
"old_path": "src/GitHubVulnerabilities2Db/Collector/AdvisoryQueryService.cs",
"new_path": "src/GitHubVulnerabilities2Db/Collector/AdvisoryQueryService.cs",
"diff": "@@ -53,7 +53,7 @@ private async Task<SecurityAdvisory> FetchAllVulnerabilitiesAsync(SecurityAdviso\nvar lastVulnerabilitiesFetchedCount = advisory.Vulnerabilities?.Edges?.Count() ?? 0;\nwhile (lastVulnerabilitiesFetchedCount == _queryBuilder.GetMaximumResultsPerRequest())\n{\n- _logger.LogInformation(\"Fetching more vulnerabilities for advisory with database key {GitHubDatabaseKey}\", advisory.DatabaseId);\n+ _logger.LogInformation(\"Fetching more vulnerabilities for advisory with database key {GitHubDatabaseKey} / GHSA ID {GhsaId}\", advisory.DatabaseId, advisory.GhsaId);\nvar queryForAdditionalVulnerabilities = _queryBuilder.CreateSecurityAdvisoryQuery(advisory);\nvar responseForAdditionalVulnerabilities = await _queryService.QueryAsync(queryForAdditionalVulnerabilities, token);\nvar advisoryWithAdditionalVulnerabilities = responseForAdditionalVulnerabilities.Data.SecurityAdvisory;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/GitHubVulnerabilities2Db/GraphQL/QueryResponse.cs",
"new_path": "src/GitHubVulnerabilities2Db/GraphQL/QueryResponse.cs",
"diff": "@@ -11,6 +11,16 @@ namespace GitHubVulnerabilities2Db.GraphQL\npublic class QueryResponse\n{\npublic QueryResponseData Data { get; set; }\n+ public List<QueryError> Errors { get; set; }\n+ }\n+\n+ /// <summary>\n+ /// The optional error details returned by the GraphQL endpoint.\n+ /// See: https://www.apollographql.com/docs/react/data/error-handling/#graphql-errors\n+ /// </summary>\n+ public class QueryError\n+ {\n+ public string Message { get; set; }\n}\n/// <summary>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/GitHubVulnerabilities2Db/GraphQL/QueryService.cs",
"new_path": "src/GitHubVulnerabilities2Db/GraphQL/QueryService.cs",
"diff": "@@ -39,7 +39,16 @@ public async Task<QueryResponse> QueryAsync(string query, CancellationToken toke\n};\nvar response = await MakeWebRequestAsync(queryJObject.ToString(), token);\n- return JsonConvert.DeserializeObject<QueryResponse>(response);\n+ var queryResponse = JsonConvert.DeserializeObject<QueryResponse>(response);\n+\n+ if (queryResponse.Errors != null && queryResponse.Errors.Count > 0)\n+ {\n+ throw new InvalidOperationException(\n+ \"The GitHub GraphQL response returned errors in the response JSON. \" +\n+ $\"Response body:{Environment.NewLine}{response}\");\n+ }\n+\n+ return queryResponse;\n}\nprivate async Task<string> MakeWebRequestAsync(string query, CancellationToken token)\n@@ -47,7 +56,15 @@ private async Task<string> MakeWebRequestAsync(string query, CancellationToken t\nusing (var request = CreateRequest(query))\nusing (var response = await _client.SendAsync(request, token))\n{\n- return await response.Content.ReadAsStringAsync();\n+ var responseBody = await response.Content.ReadAsStringAsync();\n+ if (!response.IsSuccessStatusCode)\n+ {\n+ throw new InvalidOperationException(\n+ $\"The GitHub GraphQL response returned status code {(int)response.StatusCode} {response.ReasonPhrase}. \" +\n+ $\"Response body:{Environment.NewLine}{responseBody}\");\n+ }\n+\n+ return responseBody;\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/GitHubVulnerabilities2Db/GraphQL/SecurityAdvisory.cs",
"new_path": "src/GitHubVulnerabilities2Db/GraphQL/SecurityAdvisory.cs",
"diff": "@@ -11,6 +11,7 @@ namespace GitHubVulnerabilities2Db.GraphQL\npublic class SecurityAdvisory : INode\n{\npublic int DatabaseId { get; set; }\n+ public string GhsaId { get; set; }\npublic string Permalink { get; set; }\npublic string Severity { get; set; }\npublic DateTimeOffset UpdatedAt { get; set; }\n"
},
{
"change_type": "MODIFY",
"old_path": "src/GitHubVulnerabilities2Db/Job.cs",
"new_path": "src/GitHubVulnerabilities2Db/Job.cs",
"diff": "@@ -35,6 +35,7 @@ public override async Task Run()\n{\nvar collector = _serviceProvider.GetRequiredService<IAdvisoryCollector>();\nwhile (await collector.ProcessAsync(CancellationToken.None));\n+\n}\nprotected override void ConfigureJobServices(IServiceCollection services, IConfigurationRoot configurationRoot)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/GitHubVulnerabilities2Db.Facts/QueryServiceFacts.cs",
"new_path": "tests/GitHubVulnerabilities2Db.Facts/QueryServiceFacts.cs",
"diff": "// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\nusing System;\n+using System.Collections.Generic;\n+using System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Headers;\nusing System.Text;\n@@ -56,6 +58,56 @@ public async Task Success()\nAssert.True(_handler.WasCalled);\n}\n+ [Fact]\n+ public async Task ErrorStatusCodeIsRejected()\n+ {\n+ // Arrange\n+ var query = \"someString\";\n+ _handler.ExpectedQueryContent = (new JObject { [\"query\"] = query }).ToString();\n+\n+ _handler.ExpectedEndpoint = new Uri(\"https://graphQL.net\");\n+ _configuration.GitHubGraphQLQueryEndpoint = _handler.ExpectedEndpoint;\n+\n+ _handler.ExpectedApiKey = \"patpatpat\";\n+ _configuration.GitHubPersonalAccessToken = _handler.ExpectedApiKey;\n+\n+ var response = new QueryResponse();\n+ _handler.ResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest)\n+ {\n+ Content = new StringContent(JsonConvert.SerializeObject(response))\n+ };\n+\n+ // Act & Assert\n+ var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => _service.QueryAsync(query, new CancellationToken()));\n+ Assert.True(_handler.WasCalled);\n+ Assert.Equal(\"The GitHub GraphQL response returned status code 400 Bad Request. Response body:\\r\\n{\\\"Data\\\":null,\\\"Errors\\\":null}\", ex.Message);\n+ }\n+\n+ [Fact]\n+ public async Task ErrorResponseJsonIsRejected()\n+ {\n+ // Arrange\n+ var query = \"someString\";\n+ _handler.ExpectedQueryContent = (new JObject { [\"query\"] = query }).ToString();\n+\n+ _handler.ExpectedEndpoint = new Uri(\"https://graphQL.net\");\n+ _configuration.GitHubGraphQLQueryEndpoint = _handler.ExpectedEndpoint;\n+\n+ _handler.ExpectedApiKey = \"patpatpat\";\n+ _configuration.GitHubPersonalAccessToken = _handler.ExpectedApiKey;\n+\n+ var response = new QueryResponse { Errors = new List<QueryError> { new QueryError { Message = \"Query = not great\" } } };\n+ _handler.ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)\n+ {\n+ Content = new StringContent(JsonConvert.SerializeObject(response))\n+ };\n+\n+ // Act & Assert\n+ var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => _service.QueryAsync(query, new CancellationToken()));\n+ Assert.True(_handler.WasCalled);\n+ Assert.Equal(\"The GitHub GraphQL response returned errors in the response JSON. Response body:\\r\\n{\\\"Data\\\":null,\\\"Errors\\\":[{\\\"Message\\\":\\\"Query = not great\\\"}]}\", ex.Message);\n+ }\n+\nprivate class QueryServiceHttpClientHandler : HttpClientHandler\n{\nprotected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | Fix bug around handling security advisories with 100 or more affected packages (#9279)
The original implementation used a securityAdvisory(databaseId) query which no longer exists. This switches to using GHSA ID as the parameter. |
455,741 | 27.10.2022 09:58:18 | 25,200 | 502039ef9351770e035c943edf4795c40c502e04 | correct link for email of new account verification | [
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Controllers/OrganizationsController.cs",
"new_path": "src/NuGetGallery/Controllers/OrganizationsController.cs",
"diff": "@@ -68,7 +68,7 @@ protected override Task SendNewAccountEmailAsync(User account)\nvar message = new NewAccountMessage(\nMessageServiceConfiguration,\naccount,\n- Url.ConfirmOrganizationEmail(account.Username, account.EmailConfirmationToken, relativeUrl: false));\n+ Url.ConfirmOrganizationEmail(account.Username, account.EmailConfirmationToken, relativeUrl: false, supportEmail: true));\nreturn MessageService.SendMessageAsync(message);\n}\n@@ -78,7 +78,7 @@ protected override Task SendEmailChangedConfirmationNoticeAsync(User account)\nvar message = new EmailChangeConfirmationMessage(\nMessageServiceConfiguration,\naccount,\n- Url.ConfirmOrganizationEmail(account.Username, account.EmailConfirmationToken, relativeUrl: false));\n+ Url.ConfirmOrganizationEmail(account.Username, account.EmailConfirmationToken, relativeUrl: false, supportEmail: true));\nreturn MessageService.SendMessageAsync(message);\n}\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | correct link for email of new account verification (#9284) |
455,754 | 28.10.2022 07:53:09 | -36,000 | ac65151a6650d2b55a9d628c13274553d04b6e6f | make support request issues prioritize normalized version | [
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery.Core/NuGetVersionExtensions.cs",
"new_path": "src/NuGetGallery.Core/NuGetVersionExtensions.cs",
"diff": "// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\nusing System.Text.RegularExpressions;\n+using NuGet.Services.Entities;\nusing NuGet.Versioning;\nnamespace NuGetGallery\n@@ -31,6 +32,16 @@ public static string ToFullString(string version)\nreturn version;\n}\n}\n+\n+ public static string GetNormalizedPackageVersion(Package package)\n+ {\n+ if (package == null)\n+ {\n+ return string.Empty;\n+ }\n+\n+ return string.IsNullOrEmpty(package.NormalizedVersion) ? Normalize(package.Version) : package.NormalizedVersion;\n+ }\n}\npublic static class NuGetVersionExtensions\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery.Core/Services/FIleNameHelper.cs",
"new_path": "src/NuGetGallery.Core/Services/FIleNameHelper.cs",
"diff": "@@ -29,9 +29,8 @@ public static string BuildFileName(Package package, string format, string exten\nreturn BuildFileName(\npackage.PackageRegistration.Id,\n- string.IsNullOrEmpty(package.NormalizedVersion) ?\n- NuGetVersionFormatter.Normalize(package.Version) :\n- package.NormalizedVersion, format, extension);\n+ NuGetVersionFormatter.GetNormalizedPackageVersion(package),\n+ format, extension);\n}\npublic static string BuildFileName(string id, string version, string pathTemplate, string extension)\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery.Services/SupportRequest/SupportRequestService.cs",
"new_path": "src/NuGetGallery.Services/SupportRequest/SupportRequestService.cs",
"diff": "@@ -201,7 +201,7 @@ public async Task UpdateIssueAsync(int issueId, int? assignedToId, int issueStat\nnewIssue.CreatedBy = loggedInUser;\nnewIssue.OwnerEmail = requestorEmailAddress;\nnewIssue.PackageId = package?.PackageRegistration.Id;\n- newIssue.PackageVersion = package?.Version;\n+ newIssue.PackageVersion = NuGetVersionFormatter.GetNormalizedPackageVersion(package);\nnewIssue.Reason = reason;\nnewIssue.SiteRoot = _siteRoot;\nnewIssue.UserKey = user?.Key;\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | make support request issues prioritize normalized version (#9285) |
455,736 | 03.11.2022 11:55:38 | 25,200 | 4a96d3c55777515a7dc81e9f57d9bdd2af563a4c | Return 404 when the null version is provided to the license endpoint
Address | [
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Controllers/PackagesController.cs",
"new_path": "src/NuGetGallery/Controllers/PackagesController.cs",
"diff": "@@ -1174,6 +1174,11 @@ public virtual ActionResult AtomFeed(string id, bool prerel = true)\n[HttpGet]\npublic virtual async Task<ActionResult> License(string id, string version)\n{\n+ if (version == null)\n+ {\n+ return HttpNotFound();\n+ }\n+\nvar package = _packageService.FindPackageByIdAndVersionStrict(id, version);\nif (package == null || package.PackageStatusKey == PackageStatus.Deleted)\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/NuGetGallery.Facts/Controllers/PackagesControllerFacts.cs",
"new_path": "tests/NuGetGallery.Facts/Controllers/PackagesControllerFacts.cs",
"diff": "@@ -10071,6 +10071,21 @@ public async Task GivenInvalidPackageReturns404()\nAssert.IsType<HttpNotFoundResult>(result);\n}\n+ [Fact]\n+ public async Task GivenNullVersionReturns404()\n+ {\n+ // arrange\n+ var controller = CreateController(\n+ GetConfigurationService(),\n+ packageService: _packageService);\n+\n+ // act\n+ var result = await controller.License(_packageId, version: null);\n+\n+ // assert\n+ Assert.IsType<HttpNotFoundResult>(result);\n+ }\n+\n[Fact]\npublic async Task GivenDeletedPackageReturns404()\n{\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | Return 404 when the null version is provided to the license endpoint (#9297)
Address https://github.com/NuGet/NuGetGallery/issues/9295 |
455,736 | 07.11.2022 15:16:12 | 28,800 | 65da0c0175bc3a86884967739b1cf0b4ad3ffb58 | Change VerifyGitHubVulnerabilities into a job
Progress on | [
{
"change_type": "MODIFY",
"old_path": "src/GitHubVulnerabilities2Db/GitHubVulnerabilities2Db.csproj",
"new_path": "src/GitHubVulnerabilities2Db/GitHubVulnerabilities2Db.csproj",
"diff": "<Version>2.106.0</Version>\n</PackageReference>\n</ItemGroup>\n- <ItemGroup>\n- <Content Include=\"Scripts\\nssm.exe\" />\n- </ItemGroup>\n<ItemGroup>\n<ProjectReference Include=\"..\\NuGet.Services.Entities\\NuGet.Services.Entities.csproj\">\n<Project>{6262f4fc-29be-4226-b676-db391c89d396}</Project>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/VerifyGitHubVulnerabilities/Job.cs",
"new_path": "src/VerifyGitHubVulnerabilities/Job.cs",
"diff": "@@ -25,23 +25,30 @@ namespace VerifyGitHubVulnerabilities\n{\nclass Job : JsonConfigurationJob\n{\n- private readonly HttpClient _client = new HttpClient();\n-\npublic override async Task Run()\n{\n- Console.WriteLine(\"Fetching vulnerabilities from GitHub...\");\n+ var telemetryClient = _serviceProvider.GetRequiredService<NuGet.Services.Logging.ITelemetryClient>();\n+\n+ Logger.LogInformation(\"Fetching vulnerabilities from GitHub...\");\nvar advisoryQueryService = _serviceProvider.GetRequiredService<IAdvisoryQueryService>();\nvar advisories = await advisoryQueryService.GetAdvisoriesSinceAsync(DateTimeOffset.MinValue, CancellationToken.None);\n- Console.WriteLine($\" FOUND {advisories.Count} advisories.\");\n+ Logger.LogInformation(\"Found {Count} advisories.\", advisories.Count);\n- Console.WriteLine(\"Fetching vulnerabilities from DB...\");\n+ Logger.LogInformation(\"Fetching vulnerabilities from DB...\");\nvar ingestor = _serviceProvider.GetRequiredService<IAdvisoryIngestor>();\nawait ingestor.IngestAsync(advisories.OrderBy(x => x.DatabaseId).ToList());\nvar verifier = _serviceProvider.GetRequiredService<IPackageVulnerabilitiesVerifier>();\n- Console.WriteLine(verifier.HasErrors ?\n- \"DB does not match GitHub API - see stderr output for details\" :\n- \"DB/metadata matches GitHub API!\");\n+ if (verifier.HasErrors)\n+ {\n+ Logger.LogError(\"DB/metadata does not match GitHub API - see error logs for details\");\n+ telemetryClient.TrackMetric(nameof(VerifyGitHubVulnerabilities) + \".DataIsInconsistent\", 1);\n+ }\n+ else\n+ {\n+ Logger.LogInformation(\"DB/metadata matches GitHub API!\");\n+ telemetryClient.TrackMetric(nameof(VerifyGitHubVulnerabilities) + \".DataIsConsistent\", 1);\n+ }\n}\nprotected override void ConfigureJobServices(IServiceCollection services, IConfigurationRoot configurationRoot)\n@@ -95,7 +102,7 @@ protected void ConfigureGalleryServices(ContainerBuilder containerBuilder)\nprotected void ConfigureQueryServices(ContainerBuilder containerBuilder)\n{\ncontainerBuilder\n- .RegisterInstance(_client)\n+ .RegisterInstance(new HttpClient())\n.As<HttpClient>();\ncontainerBuilder\n"
},
{
"change_type": "MODIFY",
"old_path": "src/VerifyGitHubVulnerabilities/Program.cs",
"new_path": "src/VerifyGitHubVulnerabilities/Program.cs",
"diff": "@@ -10,7 +10,7 @@ class Program\nstatic void Main(string[] args)\n{\nvar job = new Job();\n- JobRunner.RunOnce(job, args).Wait();\n+ JobRunner.Run(job, args).Wait();\n}\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/VerifyGitHubVulnerabilities/README.md",
"new_path": "src/VerifyGitHubVulnerabilities/README.md",
"diff": "## Overview\n-This is a run-once job for taking a current snapshot of the whole of GitHub's security advisory collection (pertaining to the `NUGET` ecosystem) and comparing it with the vulnerability records in the gallery database. It's designed to be run on an ad hoc basis (not an ongoing monitoring job), from the command line, with all status message streamed to `stdout` and all vulnerability differences streamed to `stderr`.\n+This is a recurring, monitoring job for taking a current snapshot of the whole of GitHub's security advisory collection (pertaining to the `NUGET` ecosystem) and comparing it with the vulnerability records in the gallery database. It's designed to interact with GitHub, the NuGet Gallery DB, and V3 metadata endpoints in a read-only manner. It just reports problems when it finds them.\n-## Running the job\n+## Running the job locally\nA typical command line will look like this:\n```\n-verifygithubvulnerabilities.exe -Configuration appsettings.json -InstrumentationKey <key> -HeartbeatIntervalSeconds 60 2>c:\\errors.txt\n+VerifyGitHubVulnerabilities.exe -Configuration appsettings.json -InstrumentationKey <key> -HeartbeatIntervalSeconds 60\n```\n-- the `2>` will direct `stderr` to a text file (a `1>` would similarly direct `stdout` but it's probably useful to have that print to console)\n-- the contents of the `appsettings.json` file will be similar (identical is fine--there are just some extra unneeded settings in them) to the settings files used for `GitHubVulnerabilities2Db`.\n-\n### Using DEV resources\nThe easiest way to run the tool if you are on the nuget.org team is to use the DEV environment resources:\n1. Install the certificate used to authenticate as our client AAD app registration into your `CurrentUser` certificate store.\n1. Clone our internal [`NuGetDeployment`](https://nuget.visualstudio.com/DefaultCollection/NuGetMicrosoft/_git/NuGetDeploymentp) repository.\n-1. Take a copy of the [DEV GitHubVulnerabilities2Db appsettings.json](https://nuget.visualstudio.com/NuGetMicrosoft/_git/NuGetDeployment?path=%2Fsrc%2FJobs%2FNuGet.Jobs.Cloud%2FJobs%2FGitHubVulnerabilities2Db%2FDEV%2Fnorthcentralus%2Fappsettings.json) file and place it in the same directory as the `verifygithubvulnerabilities.exe`. This will use our secrets to authenticate to the SQL server (this file also contains a reference to the secret used for the access token to GitHub).\n-1. Set the following property, in the `appsettings.json`, under the `\"Initialization\"` object: `\"NuGetV3Index\": \"https://apidev.nugettest.org/v3/index.json\"`.\n-1. Overwrite the Gallery DB `\"ConnectionString\"` property to be the connection string from [DEV USSC (read-only) gallery config](https://nuget.visualstudio.com/NuGetMicrosoft/_git/NuGetDeployment?path=/src/Gallery/ExpressV2/ServiceSpecs/Parameters.AS/DEV/USSC/NuGet.Gallery.Parameters.json&version=GBmaster). This provides an additional protection to ensure the job runs as read-only.\n-2. Run as per above.\n+1. Take a copy of the [DEV VerifyGitHubVulnerabilities appsettings.json](https://nuget.visualstudio.com/NuGetMicrosoft/_git/NuGetDeployment?path=%2Fsrc%2FJobs%2FNuGet.Jobs.Cloud%2FJobs%VerifyGitHubVulnerabilities%2FDEV%2Fnorthcentralus%2Fappsettings.json) file and place it in the same directory as the `VerifyGitHubVulnerabilities.exe`. This will use our secrets to authenticate to the SQL server (this file also contains a reference to the secret used for the access token to GitHub).\n+1. Run as per above.\n## Algorithm\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/VerifyGitHubVulnerabilities/Scripts/Functions.ps1",
"diff": "+Function Uninstall-NuGetService() {\n+ Param ([string]$ServiceName)\n+\n+ if (Get-Service $ServiceName -ErrorAction SilentlyContinue)\n+ {\n+ Write-Host Removing service $ServiceName...\n+ Stop-Service $ServiceName -Force\n+ sc.exe delete $ServiceName\n+ Write-Host Removed service $ServiceName.\n+ } else {\n+ Write-Host Skipping removal of service $ServiceName - no such service exists.\n+ }\n+}\n+\n+Function Install-NuGetService() {\n+ Param (\n+ [string]$ServiceName,\n+ [string]$ServiceTitle,\n+ [string]$ScriptToRun,\n+ [Parameter(Mandatory=$false)][string]$Username,\n+ [Parameter(Mandatory=$false)][string]$Password\n+ )\n+\n+ Write-Host Installing service $ServiceName...\n+\n+ $installService = \"nssm install $ServiceName $ScriptToRun\"\n+ cmd /C $installService\n+\n+ Set-Service -Name $ServiceName -DisplayName \"$ServiceTitle - $ServiceName\" -Description \"Runs $ServiceTitle.\" -StartupType Automatic\n+ sc.exe failure $ServiceName reset= 30 actions= restart/5000\n+\n+ if ($Username) {\n+ Write-Host Running service under specific credentials.\n+ sc.exe config \"$ServiceName\" obj= \"$Username\" password= \"$Password\"\n+ }\n+\n+ # Run service\n+ net start $ServiceName\n+\n+ Write-Host Installed service $ServiceName.\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/VerifyGitHubVulnerabilities/Scripts/PostDeploy.ps1",
"diff": "+. .\\Functions.ps1\n+\n+$jobsToInstall = $OctopusParameters[\"Jobs.ServiceNames\"].Split(\"{,}\")\n+\n+Write-Host Installing services...\n+\n+$currentDirectory = [string](Get-Location)\n+\n+$jobsToInstall.Split(\"{;}\") | %{\n+ $serviceName = $_\n+ $serviceTitle = $OctopusParameters[\"Jobs.$serviceName.Title\"]\n+ $serviceUsername = $OctopusParameters[\"Jobs.$serviceName.Username\"]\n+ $servicePassword = $OctopusParameters[\"Jobs.$serviceName.Password\"]\n+ $scriptToRun = $OctopusParameters[\"Jobs.$serviceName.Script\"]\n+ $scriptToRun = \"$currentDirectory\\$scriptToRun\"\n+\n+ Install-NuGetService -ServiceName $serviceName -ServiceTitle $serviceTitle -ScriptToRun $scriptToRun -Username $serviceUsername -Password $servicePassword\n+}\n+\n+Write-Host Installed services.\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/VerifyGitHubVulnerabilities/Scripts/PreDeploy.ps1",
"diff": "+. .\\Functions.ps1\n+\n+$jobsToInstall = $OctopusParameters[\"Jobs.ServiceNames\"].Split(\"{,}\")\n+\n+Write-Host Removing services...\n+\n+$jobsToInstall.Split(\"{;}\") | %{\n+ Uninstall-NuGetService -ServiceName $_\n+}\n+\n+Write-Host Removed services.\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": "src/VerifyGitHubVulnerabilities/Scripts/nssm.exe",
"new_path": "src/VerifyGitHubVulnerabilities/Scripts/nssm.exe",
"diff": "Binary files /dev/null and b/src/VerifyGitHubVulnerabilities/Scripts/nssm.exe differ\n"
},
{
"change_type": "MODIFY",
"old_path": "src/VerifyGitHubVulnerabilities/Verify/PackageVulnerabilitiesVerifier.cs",
"new_path": "src/VerifyGitHubVulnerabilities/Verify/PackageVulnerabilitiesVerifier.cs",
"diff": "using System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\n+using Microsoft.Extensions.Logging;\nusing NuGet.Configuration;\nusing NuGet.Protocol;\nusing NuGet.Protocol.Core.Types;\n@@ -21,14 +22,17 @@ public class PackageVulnerabilitiesVerifier : IPackageVulnerabilitiesVerifier\n{\nprivate readonly VerifyGitHubVulnerabilitiesConfiguration _configuration;\nprivate readonly IEntitiesContext _entitiesContext;\n+ private readonly ILogger<PackageVulnerabilitiesVerifier> _logger;\nprivate Lazy<Task<PackageMetadataResource>> _packageMetadataResource;\nprivate Dictionary<string, IEnumerable<IPackageSearchMetadata>> _packageMetadata;\nprivate static readonly SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1);\n- public PackageVulnerabilitiesVerifier(VerifyGitHubVulnerabilitiesConfiguration configuration,\n- IEntitiesContext entitiesContext)\n+ public PackageVulnerabilitiesVerifier(\n+ VerifyGitHubVulnerabilitiesConfiguration configuration,\n+ IEntitiesContext entitiesContext,\n+ ILogger<PackageVulnerabilitiesVerifier> logger)\n{\n_configuration = configuration;\nif (_configuration.VerifyDatabase)\n@@ -38,6 +42,7 @@ public class PackageVulnerabilitiesVerifier : IPackageVulnerabilitiesVerifier\n_packageMetadata = new Dictionary<string, IEnumerable<IPackageSearchMetadata>>();\n_packageMetadataResource = new Lazy<Task<PackageMetadataResource>>(InitializeMetadataResourceAsync);\n+ _logger = logger;\n}\npublic bool HasErrors { get; private set; }\n@@ -51,7 +56,7 @@ public Task UpdateVulnerabilityAsync(PackageVulnerability vulnerability, bool wi\n{\nif (vulnerability == null)\n{\n- Console.Error.WriteLine(\"Null vulnerability passed to verifier! Continuing...\");\n+ _logger.LogWarning(\"Null vulnerability passed to verifier! Continuing...\");\nreturn Task.CompletedTask;\n}\n@@ -73,7 +78,10 @@ public Task UpdateVulnerabilityAsync(PackageVulnerability vulnerability, bool wi\nprivate void VerifyVulnerabilityInDatabase(PackageVulnerability vulnerability, bool withdrawn)\n{\n- Console.WriteLine($\"[Database] Verifying vulnerability {vulnerability.GitHubDatabaseKey}.\");\n+ _logger.LogInformation(\n+ \"[Database] Verifying vulnerability {GitHubDatabaseKey} (advisory URL: {AdvisoryUrl}).\",\n+ vulnerability.GitHubDatabaseKey,\n+ vulnerability.AdvisoryUrl);\nvar existingVulnerability = _entitiesContext.Vulnerabilities\n.Include(v => v.AffectedRanges)\n@@ -83,9 +91,9 @@ private void VerifyVulnerabilityInDatabase(PackageVulnerability vulnerability, b\n{\nif (existingVulnerability != null)\n{\n- Console.Error.WriteLine(withdrawn ?\n- $@\"[Database] Vulnerability advisory {vulnerability.GitHubDatabaseKey} was withdrawn and should not be in DB!\" :\n- $@\"[Database] Vulnerability advisory {vulnerability.GitHubDatabaseKey} affects no packages and should not be in DB!\");\n+ _logger.LogError(withdrawn ?\n+ \"[Database] Vulnerability advisory {GitHubDatabaseKey} was withdrawn and should not be in DB!\" :\n+ \"[Database] Vulnerability advisory {GitHubDatabaseKey} affects no packages and should not be in DB!\", vulnerability.GitHubDatabaseKey);\nHasErrors = true;\n}\n@@ -94,48 +102,58 @@ private void VerifyVulnerabilityInDatabase(PackageVulnerability vulnerability, b\nif (existingVulnerability == null)\n{\n- Console.Error.WriteLine($\"[Database] Cannot find vulnerability {vulnerability.GitHubDatabaseKey} in DB!\");\n+ _logger.LogError(\"[Database] Cannot find vulnerability {GitHubDatabaseKey} in DB!\", vulnerability.GitHubDatabaseKey);\nHasErrors = true;\nreturn;\n}\nif (existingVulnerability.Severity != vulnerability.Severity)\n{\n- Console.Error.WriteLine(\n- $@\"[Database] Vulnerability advisory {vulnerability.GitHubDatabaseKey\n- }, severity does not match! GitHub: {vulnerability.Severity}, DB: {existingVulnerability.Severity}\");\n+ _logger.LogError(\n+ \"[Database] Vulnerability advisory {GitHubDatabaseKey}, severity does not match! GitHub: {GitHubSeverity}, DB: {DbSeverity}\",\n+ vulnerability.GitHubDatabaseKey,\n+ vulnerability.Severity,\n+ existingVulnerability.Severity);\nHasErrors = true;\n}\nif (existingVulnerability.AdvisoryUrl != vulnerability.AdvisoryUrl)\n{\n- Console.Error.WriteLine(\n- $@\"[Database] Vulnerability advisory {vulnerability.GitHubDatabaseKey\n- }, advisory URL does not match! GitHub: {vulnerability.AdvisoryUrl}, DB: { existingVulnerability.AdvisoryUrl}\");\n+ _logger.LogError(\n+ \"[Database] Vulnerability advisory {GitHubDatabaseKey}, advisory URL does not match! GitHub: {GitHubAdvisoryUrl}, DB: {DbAdvisoryUrl}\",\n+ vulnerability.GitHubDatabaseKey,\n+ vulnerability.AdvisoryUrl,\n+ existingVulnerability.AdvisoryUrl);\nHasErrors = true;\n}\nforeach (var range in vulnerability.AffectedRanges)\n{\n- Console.WriteLine($\"[Database] Verifying range affecting {range.PackageId} {range.PackageVersionRange}.\");\n+ _logger.LogInformation(\"[Database] Verifying range affecting {PackageId} {PackageVersionRange}.\", range.PackageId, range.PackageVersionRange);\nvar existingRange = existingVulnerability.AffectedRanges\n.SingleOrDefault(r => r.PackageId == range.PackageId && r.PackageVersionRange == range.PackageVersionRange);\nif (existingRange == null)\n{\n- Console.Error.WriteLine(\n- $@\"[Database] Vulnerability advisory {vulnerability.GitHubDatabaseKey\n- }, cannot find range {range.PackageId} {range.PackageVersionRange} in DB!\");\n+ _logger.LogError(\n+ \"[Database] Vulnerability advisory {GitHubDatabaseKey}, cannot find range {PackageId} {PackageVersionRange} in DB!\",\n+ vulnerability.GitHubDatabaseKey,\n+ range.PackageId,\n+ range.PackageVersionRange);\nHasErrors = true;\ncontinue;\n}\nif (existingRange.FirstPatchedPackageVersion != range.FirstPatchedPackageVersion)\n{\n- Console.Error.WriteLine(\n- $@\"[Database] Vulnerability advisory {vulnerability.GitHubDatabaseKey\n- }, range {range.PackageId} {range.PackageVersionRange}, first patched version does not match! GitHub: {\n- range.FirstPatchedPackageVersion}, DB: {range.FirstPatchedPackageVersion}\");\n+ _logger.LogError(\n+ \"[Database] Vulnerability advisory {GitHubDatabaseKey}, range {PackageId} {PackageVersionRange}, \" +\n+ \"first patched version does not match! GitHub: {GitHubFirstPatchedPackageVersion}, DB: {DbFirstPatchedPackageVersion}\",\n+ vulnerability.GitHubDatabaseKey,\n+ range.PackageVersionRange,\n+ range.PackageVersionRange,\n+ range.FirstPatchedPackageVersion,\n+ existingRange.FirstPatchedPackageVersion);\nHasErrors = true;\n}\n@@ -150,10 +168,13 @@ private void VerifyVulnerabilityInDatabase(PackageVulnerability vulnerability, b\nvar version = NuGetVersion.Parse(package.NormalizedVersion);\nif (versionRange.Satisfies(version) != package.VulnerablePackageRanges.Contains(existingRange))\n{\n- Console.Error.WriteLine(\n- $@\"[Database] Vulnerability advisory {vulnerability.GitHubDatabaseKey\n- }, range {range.PackageId} {range.PackageVersionRange}, package {package.NormalizedVersion\n- } is not properly marked vulnerable to vulnerability!\");\n+ _logger.LogError(\n+ \"[Database] Vulnerability advisory {GitHubDatabaseKey}, \" +\n+ \"range {PackageId} {PackageVersionRange}, package {NormalizedVersion} is not properly marked vulnerable to vulnerability!\",\n+ vulnerability.GitHubDatabaseKey,\n+ range.PackageId,\n+ range.PackageVersionRange,\n+ package.NormalizedVersion);\nHasErrors = true;\n}\n}\n@@ -162,7 +183,10 @@ private void VerifyVulnerabilityInDatabase(PackageVulnerability vulnerability, b\nprivate Task VerifyVulnerabilityInMetadataAsync(PackageVulnerability gitHubAdvisory)\n{\n- Console.WriteLine($\"[Metadata] Verifying vulnerability {gitHubAdvisory.GitHubDatabaseKey}.\");\n+ _logger.LogInformation(\n+ \"[Metadata] Verifying vulnerability {GitHubDatabaseKey} (advisory URL: {AdvisoryUrl}).\",\n+ gitHubAdvisory.GitHubDatabaseKey,\n+ gitHubAdvisory.AdvisoryUrl);\nif (gitHubAdvisory.AffectedRanges == null || !gitHubAdvisory.AffectedRanges.Any())\n{\n@@ -235,9 +259,12 @@ private Task VerifyVulnerabilityInMetadataAsync(PackageVulnerability gitHubAdvis\n{\nif (!hasTheVulnerability)\n{\n- Console.Error.WriteLine(\n- $@\"[Metadata] Vulnerability advisory {advisoryDatabaseKey\n- }, version {versionMetadata.Identity.Version} of package {packageId} is not marked vulnerable and is in a vulnerable range!\");\n+ _logger.LogError(\n+ \"[Metadata] Vulnerability advisory {AdvisoryDatabaseKey}, version {Version} of package {PackageId} \" +\n+ \"is not marked vulnerable and is in a vulnerable range!\",\n+ advisoryDatabaseKey,\n+ versionMetadata.Identity.Version,\n+ packageId);\nHasErrors = true;\n}\n@@ -246,9 +273,12 @@ private Task VerifyVulnerabilityInMetadataAsync(PackageVulnerability gitHubAdvis\n.FirstOrDefault(v => v.Severity != (int)advisorySeverity);\nif (firstSeverityMismatch != null)\n{\n- Console.Error.WriteLine(\n- $@\"[Metadata] Vulnerability advisory {advisoryDatabaseKey\n- }, severities has at least one mismatch! GitHub: {advisorySeverity}, Metadata: {firstSeverityMismatch.Severity}\");\n+ _logger.LogError(\n+ \"[Metadata] Vulnerability advisory {AdvisoryDatabaseKey}, severities has at least one mismatch! \" +\n+ \"GitHub: {GitHubAdvisorySeverity}, Metadata: {FirstSeverityMismatchSeverity}\",\n+ advisoryDatabaseKey,\n+ advisorySeverity,\n+ firstSeverityMismatch.Severity);\nHasErrors = true;\n}\n}\n@@ -256,9 +286,12 @@ private Task VerifyVulnerabilityInMetadataAsync(PackageVulnerability gitHubAdvis\n{\nif (hasTheVulnerability)\n{\n- Console.Error.WriteLine(\n- $@\"[Metadata] Vulnerability advisory {advisoryDatabaseKey\n- }, version {versionMetadata.Identity.Version} of package {packageId} is marked vulnerable and is not in a vulnerable range!\");\n+ _logger.LogError(\n+ \"[Metadata] Vulnerability advisory {AdvisoryDatabaseKey}, version {Version} of package {PackageId} \" +\n+ \"is marked vulnerable and is not in a vulnerable range!\",\n+ advisoryDatabaseKey,\n+ versionMetadata.Identity.Version,\n+ packageId);\nHasErrors = true;\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/VerifyGitHubVulnerabilities/VerifyGitHubVulnerabilities.csproj",
"new_path": "src/VerifyGitHubVulnerabilities/VerifyGitHubVulnerabilities.csproj",
"diff": "</ItemGroup>\n<ItemGroup>\n<None Include=\"App.config\" />\n+ <None Include=\"README.md\" />\n+ <None Include=\"Scripts\\Functions.ps1\" />\n+ <None Include=\"Scripts\\PostDeploy.ps1\" />\n+ <None Include=\"Scripts\\PreDeploy.ps1\" />\n+ <None Include=\"VerifyGitHubVulnerabilities.nuspec\" />\n</ItemGroup>\n<ItemGroup>\n<PackageReference Include=\"NuGet.Jobs.Common\">\n<Name>NuGetGallery.Services</Name>\n</ProjectReference>\n</ItemGroup>\n+ <ItemGroup>\n+ <None Include=\"Scripts\\nssm.exe\" />\n+ </ItemGroup>\n<PropertyGroup>\n<SignPath>..\\..\\build</SignPath>\n<SignPath Condition=\"'$(BUILD_SOURCESDIRECTORY)' != ''\">$(BUILD_SOURCESDIRECTORY)\\build</SignPath>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/VerifyGitHubVulnerabilities/VerifyGitHubVulnerabilities.nuspec",
"new_path": "src/VerifyGitHubVulnerabilities/VerifyGitHubVulnerabilities.nuspec",
"diff": "</metadata>\n<files>\n<file src=\"bin\\$configuration$\\**\\*.*\" target=\"bin\"/>\n+\n+ <file src=\"Scripts\\Functions.ps1\" />\n+ <file src=\"Scripts\\PreDeploy.ps1\" />\n+ <file src=\"Scripts\\PostDeploy.ps1\" />\n+ <file src=\"Scripts\\nssm.exe\" />\n</files>\n</package>\n\\ No newline at end of file\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | Change VerifyGitHubVulnerabilities into a job (#9298)
Progress on https://github.com/NuGet/Engineering/issues/4512 |
455,754 | 09.11.2022 07:25:04 | -36,000 | a9d6c6153885501730f9ef38bf9639dc13e3861f | Swap Package manager and dotnet CLI tabs in display package UI, making dotnet CLI the default | [
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Views/Packages/DisplayPackage.cshtml",
"new_path": "src/NuGetGallery/Views/Packages/DisplayPackage.cshtml",
"diff": "{\npackageManagers = new PackageManagerViewModel[]\n{\n+ new PackageManagerViewModel(\".NET CLI\")\n+ {\n+ Id = \"dotnet-cli\",\n+ CommandPrefix = \"> \",\n+ InstallPackageCommands = new [] { string.Format(\"dotnet add package {0} --version {1}\", Model.Id, Model.Version) },\n+ },\n+\nnew PackageManagerViewModel(\"Package Manager\")\n{\nId = \"package-manager\",\n},\n- new PackageManagerViewModel(\".NET CLI\")\n- {\n- Id = \"dotnet-cli\",\n- CommandPrefix = \"> \",\n- InstallPackageCommands = new [] { string.Format(\"dotnet add package {0} --version {1}\", Model.Id, Model.Version) },\n- },\n-\nnew PackageManagerViewModel(\"PackageReference\")\n{\nId = \"package-reference\",\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | Swap Package manager and dotnet CLI tabs in display package UI, making dotnet CLI the default (#9302) |
455,778 | 15.11.2022 01:45:40 | 0 | f472850325992ea213b272069ef1c5d5254b1b69 | [A11y] Removed incorrect role attribute from breadcrumb headings | [
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/App_Code/ViewHelpers.cshtml",
"new_path": "src/NuGetGallery/App_Code/ViewHelpers.cshtml",
"diff": "@@ -588,10 +588,10 @@ var hlp = new AccordionHelper(name, formModelStatePrefix, expanded, page);\n@helper Breadcrumb(bool showDivider, params Func<MvcHtmlString, HelperResult>[] segments)\n{\n- <h1 role=\"list\" class=\"ms-font-xl breadcrumb-title\">\n+ <h1 class=\"ms-font-xl breadcrumb-title\">\n@for (int i = 0; i < segments.Length; i++)\n{\n- <span role=\"listitem\" class=\"ms-noWrap\">@segments[i](MvcHtmlString.Empty)</span>\n+ <span class=\"ms-noWrap\">@segments[i](MvcHtmlString.Empty)</span>\nif (i < segments.Length - 1)\n{\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | [A11y] Removed incorrect role attribute from breadcrumb headings (#9311) |
455,784 | 17.11.2022 15:22:37 | 28,800 | a65d4cf7a312228e0137c5d445937e08796bc2fc | make aria-hidden elements not focusable | [
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Views/Packages/DisplayPackage.cshtml",
"new_path": "src/NuGetGallery/Views/Packages/DisplayPackage.cshtml",
"diff": "@if (Model.IsVerified.HasValue && Model.IsVerified.Value)\n{\n<span class=\"prefix-reserve-title\" aria-hidden=\"true\">\n- <img class=\"reserved-indicator\" aria-hidden=\"true\"\n+ <img class=\"reserved-indicator\" aria-hidden=\"true\" tabindex=\"-1\"\nsrc=\"~/Content/gallery/img/reserved-indicator.svg\"\[email protected](Url.Absolute(\"~/Content/gallery/img/reserved-indicator-25x25.png\"))\ndata-content=\"@Strings.ReservedNamespace_ReservedIndicatorTooltip\" tabindex=\"0\"\nalt=\"@Strings.ReservedNamespace_ReservedIndicatorTooltip\"/>\n- <a href=\"https://docs.microsoft.com/en-us/nuget/nuget-org/id-prefix-reservation\" class=\"prefix-reserve-label\" ari-hidden=\"true\">\n+ <a href=\"https://docs.microsoft.com/en-us/nuget/nuget-org/id-prefix-reservation\" class=\"prefix-reserve-label\" aria-hidden=\"true\" tabindex=\"-1\">\nPrefix Reserved\n</a>\n</span>\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | make aria-hidden elements not focusable (#9314) |
455,740 | 21.11.2022 16:26:45 | -3,600 | 3db28166d7943f7812a86dfb3a40e3f0047384cd | Changed `dotnet new` example
The syntax has changed in .NET 7. Since .NET 7 is GA'd and is being actively adopted, we'll update NuGet.org to reflect that. | [
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Views/Packages/DisplayPackage.cshtml",
"new_path": "src/NuGetGallery/Views/Packages/DisplayPackage.cshtml",
"diff": "{\nId = \"dotnet-cli\",\nCommandPrefix = \"> \",\n- InstallPackageCommands = new [] { string.Format(\"dotnet new --install {0}::{1}\", Model.Id, Model.Version) },\n+ InstallPackageCommands = new [] { string.Format(\"dotnet new install {0}::{1}\", Model.Id, Model.Version) },\nAlertLevel = AlertLevel.Info,\n- AlertMessage = \"This package contains a <a href='https://aka.ms/dotnet-new'>.NET Core Template Package</a> you can call from the shell/command line.\",\n+ AlertMessage = \"This package contains a <a href='https://aka.ms/dotnet-new'>.NET Template Package</a> you can call from the shell/command line.\",\n}\n};\n}\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | Changed `dotnet new` example (#9309)
Co-authored-by: Joel Verhagen <[email protected]>
The syntax has changed in .NET 7. Since .NET 7 is GA'd and is being actively adopted, we'll update NuGet.org to reflect that. |
455,736 | 12.12.2022 10:40:17 | 28,800 | 3f92a094e1cb0878a6e0da191805fbfe64b1eee8 | Audit the AddCredential action after we commit to the DB
Resolve | [
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery.Services/Authentication/AuthenticationService.cs",
"new_path": "src/NuGetGallery.Services/Authentication/AuthenticationService.cs",
"diff": "@@ -473,6 +473,9 @@ public virtual async Task ReplaceCredential(User user, Credential credential)\n{\nawait ReplaceCredentialInternal(user, credential);\nawait Entities.SaveChangesAsync();\n+\n+ await Auditing.SaveAuditRecordAsync(new UserAuditRecord(\n+ user, AuditedUserAction.AddCredential, credential));\n}\npublic virtual async Task<Credential> ResetPasswordWithToken(string username, string token, string newPassword)\n@@ -501,6 +504,10 @@ public virtual async Task<Credential> ResetPasswordWithToken(string username, st\nuser.FailedLoginCount = 0;\nuser.LastFailedLoginUtc = null;\nawait Entities.SaveChangesAsync();\n+\n+ await Auditing.SaveAuditRecordAsync(new UserAuditRecord(\n+ user, AuditedUserAction.AddCredential, cred));\n+\nreturn cred;\n}\n@@ -590,6 +597,10 @@ public virtual async Task<bool> ChangePassword(User user, string oldPassword, st\n// Save changes\nawait Entities.SaveChangesAsync();\n+\n+ await Auditing.SaveAuditRecordAsync(new UserAuditRecord(\n+ user, AuditedUserAction.AddCredential, passwordCredential));\n+\nreturn true;\n}\n@@ -623,10 +634,10 @@ public virtual async Task AddCredential(User user, Credential credential)\nthrow new InvalidOperationException(ServicesStrings.OrganizationsCannotCreateCredentials);\n}\n- await Auditing.SaveAuditRecordAsync(new UserAuditRecord(user, AuditedUserAction.AddCredential, credential));\nuser.Credentials.Add(credential);\nawait Entities.SaveChangesAsync();\n+ await Auditing.SaveAuditRecordAsync(new UserAuditRecord(user, AuditedUserAction.AddCredential, credential));\n_telemetryService.TrackNewCredentialCreated(user, credential);\n}\n@@ -838,9 +849,6 @@ private async Task ReplaceCredentialInternal(User user, Credential credential)\n}\nuser.Credentials.Add(credential);\n-\n- await Auditing.SaveAuditRecordAsync(new UserAuditRecord(\n- user, AuditedUserAction.AddCredential, credential));\n}\nprivate static CredentialKind GetCredentialKind(string type)\n@@ -1024,15 +1032,20 @@ private async Task MigrateCredentials(User user, List<Credential> creds, string\nawait Auditing.SaveAuditRecordAsync(new UserAuditRecord(user, AuditedUserAction.RemoveCredential, toRemove));\n// Now add one if there are no credentials left\n+ Credential newCred = null;\nif (creds.Count == 0)\n{\n- var newCred = _credentialBuilder.CreatePasswordCredential(password);\n- await Auditing.SaveAuditRecordAsync(new UserAuditRecord(user, AuditedUserAction.AddCredential, newCred));\n+ newCred = _credentialBuilder.CreatePasswordCredential(password);\nuser.Credentials.Add(newCred);\n}\n// Save changes, if any\nawait Entities.SaveChangesAsync();\n+\n+ if (newCred != null)\n+ {\n+ await Auditing.SaveAuditRecordAsync(new UserAuditRecord(user, AuditedUserAction.AddCredential, newCred));\n+ }\n}\n}\n}\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/NuGetGallery.Facts/Authentication/AuthenticationServiceFacts.cs",
"new_path": "tests/NuGetGallery.Facts/Authentication/AuthenticationServiceFacts.cs",
"diff": "using NuGetGallery.Auditing;\nusing NuGetGallery.Authentication.Providers;\nusing NuGetGallery.Authentication.Providers.MicrosoftAccount;\n+using NuGetGallery.Configuration;\n+using NuGetGallery.Diagnostics;\nusing NuGetGallery.Framework;\nusing NuGetGallery.Infrastructure.Authentication;\nusing Xunit;\n@@ -2071,6 +2073,51 @@ public async Task WritesAuditRecordForTheNewCredential()\nar.AffectedCredential[0].Type == cred.Type &&\nar.AffectedCredential[0].Identity == cred.Identity));\n}\n+\n+ [Fact]\n+ public async Task WritesAuditRecordAfterDbCommit()\n+ {\n+ // Arrange\n+ var entitiesContext = new Mock<IEntitiesContext>();\n+ var auditingService = new Mock<IAuditingService>();\n+ var credentialBuilder = new CredentialBuilder();\n+\n+ var authService = new AuthenticationService(\n+ entitiesContext.Object,\n+ Get<IAppConfiguration>(),\n+ Get<IDiagnosticsService>(),\n+ auditingService.Object,\n+ Enumerable.Empty<Authenticator>(),\n+ credentialBuilder,\n+ Get<ICredentialValidator>(),\n+ Get<IDateTimeProvider>(),\n+ Get<ITelemetryService>(),\n+ Get<IContentObjectService>(),\n+ Get<IFeatureFlagService>());\n+ var operations = new List<string>();\n+\n+ var fakes = Get<Fakes>();\n+ var user = fakes.CreateUser(\"test\", credentialBuilder.CreatePasswordCredential(Fakes.Password));\n+ var cred = credentialBuilder.CreateExternalCredential(\"flarg\", \"glarb\", \"blarb\");\n+ Mock\n+ .Get(authService.Auditing)\n+ .Setup(x => x.SaveAuditRecordAsync(It.IsAny<AuditRecord>()))\n+ .Returns(Task.CompletedTask)\n+ .Callback(() => operations.Add(nameof(IAuditingService.SaveAuditRecordAsync)));\n+ Mock\n+ .Get(authService.Entities)\n+ .Setup(x => x.SaveChangesAsync())\n+ .ReturnsAsync(() => 0)\n+ .Callback(() => operations.Add(nameof(IEntitiesContext.SaveChangesAsync)));\n+\n+ // Act\n+ await authService.AddCredential(user, cred);\n+\n+ // Assert\n+ Assert.Equal(\n+ new List<string> { nameof(IEntitiesContext.SaveChangesAsync), nameof(IAuditingService.SaveAuditRecordAsync) },\n+ operations);\n+ }\n}\npublic class TheDescribeCredentialMethod : TestContainer\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | Audit the AddCredential action after we commit to the DB (#9324)
Resolve https://github.com/NuGet/Engineering/issues/4660 |
455,736 | 14.12.2022 16:27:27 | 28,800 | e031d697f49eec9975cc586cb15cd29868c118d3 | Selectively render the vulnerable element on manage packages page
Progress on | [
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Scripts/gallery/common.js",
"new_path": "src/NuGetGallery/Scripts/gallery/common.js",
"diff": "nuget.setPopovers = function () {\nvar popoverElement = $(this);\n- var popoverElementDom = popoverElement.get(0);\n+ var popoverElementDom = this;\nvar originalLabel = popoverElementDom.ariaLabel;\nvar popoverHideTimeMS = 2000;\nvar popoverFadeTimeMS = 200;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Views/Users/Packages.cshtml",
"new_path": "src/NuGetGallery/Views/Users/Packages.cshtml",
"diff": "{\nvar title = \"This version has at least one known vulnerability. Click on the package name for details.\";\n<td class=\"package-icon-cell\">\n- <span class=\"package-warning-icon\" aria-label=\"@title\" data-content=\"@title\" data-bind=\"visible: IsVulnerable\" tabindex=\"0\">\n+ <!-- ko if: IsVulnerable -->\n+ <span class=\"package-warning-icon\" aria-label=\"@title\" data-content=\"@title\" tabindex=\"0\">\n<i class=\"ms-Icon ms-Icon--Warning package-icon\"></i>\n</span>\n+ <!-- /ko -->\n</td>\n}\n<td class=\"text-right align-middle package-controls\">\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | Selectively render the vulnerable element on manage packages page (#9328)
Progress on https://github.com/NuGet/NuGetGallery/issues/5877 |
455,779 | 26.12.2022 23:23:09 | -28,800 | db1bdb26b720e76a761d686cde1e1b53902f3ce0 | Add document about how to deploy locally | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -27,9 +27,26 @@ Now run the NuGet Gallery:\nRefer to [our documentation](./docs/) for information on how to develop the frontend, use AAD, and more.\n## Deploy\n+### Deploy to Azure\nYou will find instructions on how to deploy the Gallery to Azure [here](https://github.com/NuGet/NuGetGallery/blob/master/docs/Deploying/README.md).\n+### Deploy locally\n+After you succeed in running the NuGet Gallery, you can create a publish profile to deploy locally (such as your local Windows computer).\n+\n+The steps are:\n+1. Select the `NuGetGallery` project in Solution Explore of Visual Studio.\n+2. Right click the project, and then click `Publish` in the pop-up menu. Create a publish profile and make sure the Target is set to `Folder`.\n+3. Copy the contents of the `Target Location` to any folder you want. For the following example, assume the folder is `C:\\ContosoSoftware\\NuGetGallery`.\n+4. Execute the command below to start the web app (note that the parameter `/path` of iisexpress.exe only supports absolute paths on Windows).\n+ ```cmd\n+ \"C:\\Program Files\\IIS Express\\iisexpress.exe\" /path:C:\\ContosoSoftware\\NuGetGallery\n+ ```\n+\n+Now you can access the local website with a web browser. The URL is `https://localhost`.\n+\n+After you deploy it, you don't need using Visual Studio to run it anymore.\n+\n## Contribute\nIf you find a bug with the gallery, please visit the [Issue tracker](https://github.com/NuGet/NuGetGallery/issues) and\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | Add document about how to deploy locally (#9333) |
455,736 | 03.01.2023 14:09:51 | 21,600 | e8c507babf86a5750214b024aedd652dc205eb84 | Move the error message container outside of the Upload section
Fix | [
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Views/Packages/UploadPackage.cshtml",
"new_path": "src/NuGetGallery/Views/Packages/UploadPackage.cshtml",
"diff": "<a href=\"https://docs.microsoft.com/nuget/create-packages/package-authoring-best-practices\" alt=\"Best Practices\" aria-label=\"Read here about publishing packages\">Best Practices</a> page.\n</p>\n</div>\n+\n+ <div id=\"validation-failure-container\" class=\"hidden\">\n+ </div>\n+\n<div id=\"upload-package-container\">\n<h2>\n<a href=\"#\" role=\"button\" data-toggle=\"collapse\" data-target=\"#upload-package-form\"\n<div id=\"upload-progress-bar-container\" class=\"progress hidden\">\n<div id=\"upload-progress-bar\" class=\"progress-bar active\" role=\"progressbar\" aria-valuemin=\"0\" aria-valuemax=\"100\"></div>\n</div>\n-\n- <div id=\"validation-failure-container\" class=\"hidden\">\n- </div>\n</div>\n</div>\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | Move the error message container outside of the Upload section (#9338)
Fix https://github.com/NuGet/NuGetGallery/issues/9336 |
455,736 | 09.01.2023 09:25:30 | 18,000 | d18bf1c5ea78d472bc43553055a9560562c18037 | Remove the client secret from AAD V2 authenticator
We were only ever using the id_token which contains enough detail for NuGet.org sign in. The code response is not used.
Progress on | [
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery.Services/Authentication/Providers/AzureActiveDirectoryV2/AzureActiveDirectoryV2Authenticator.cs",
"new_path": "src/NuGetGallery.Services/Authentication/Providers/AzureActiveDirectoryV2/AzureActiveDirectoryV2Authenticator.cs",
"diff": "@@ -101,12 +101,13 @@ protected override void AttachToOwinApp(IGalleryConfigurationService config, IAp\nRedirectUri = siteRoot + _callbackPath,\nPostLogoutRedirectUri = siteRoot,\nScope = OpenIdConnectScope.OpenIdProfile + \" email\",\n- ResponseType = OpenIdConnectResponseType.CodeIdToken,\n+ ResponseType = OpenIdConnectResponseType.IdToken,\nTokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateIssuer = false },\nNotifications = new OpenIdConnectAuthenticationNotifications\n{\nAuthenticationFailed = AuthenticationFailed,\n- RedirectToIdentityProvider = RedirectToIdentityProvider\n+ RedirectToIdentityProvider = RedirectToIdentityProvider,\n+ AuthorizationCodeReceived = AuthorizationCodeReceived,\n}\n};\n@@ -271,5 +272,13 @@ private AuthenticationProperties GetAuthenticationPropertiesFromProtocolMessage(\nvar authenticationPropertiesEncodedString = message.State.Split('=');\nreturn options.StateDataFormat.Unprotect(authenticationPropertiesEncodedString[1]);\n}\n+\n+ private Task AuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)\n+ {\n+ // Explicitly set the access_token to null. The access_token is used for authorized requests to AAD on\n+ // behalf of the end user. We do not use this feature. We only use the id_token.\n+ context.HandleCodeRedemption(accessToken: null, idToken: context.JwtSecurityToken.RawData);\n+ return Task.CompletedTask;\n+ }\n}\n}\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery.Services/Authentication/Providers/AzureActiveDirectoryV2/AzureActiveDirectoryV2AuthenticatorConfiguration.cs",
"new_path": "src/NuGetGallery.Services/Authentication/Providers/AzureActiveDirectoryV2/AzureActiveDirectoryV2AuthenticatorConfiguration.cs",
"diff": "@@ -12,7 +12,6 @@ namespace NuGetGallery.Authentication.Providers.AzureActiveDirectoryV2\npublic class AzureActiveDirectoryV2AuthenticatorConfiguration : AuthenticatorConfiguration\n{\npublic string ClientId { get; set; }\n- public string ClientSecret { get; set; }\npublic AzureActiveDirectoryV2AuthenticatorConfiguration()\n{\n@@ -31,7 +30,7 @@ public override void ApplyToOwinSecurityOptions(AuthenticationOptions options)\n// the auth flow.\nopenIdOptions.AuthenticationMode = AuthenticationMode.Passive;\n- // Make sure ClientId and ClientSecret is configured\n+ // Make sure ClientId is configured\nif (String.IsNullOrEmpty(ClientId))\n{\nthrow new ConfigurationErrorsException(String.Format(\n@@ -40,16 +39,7 @@ public override void ApplyToOwinSecurityOptions(AuthenticationOptions options)\n\"Auth.CommonAuth.ClientId\"));\n}\n- if (String.IsNullOrEmpty(ClientSecret))\n- {\n- throw new ConfigurationErrorsException(String.Format(\n- CultureInfo.CurrentCulture,\n- ServicesStrings.MissingRequiredConfigurationValue,\n- \"Auth.CommonAuth.ClientSecret\"));\n- }\n-\nopenIdOptions.ClientId = ClientId;\n- openIdOptions.ClientSecret = ClientSecret;\nopenIdOptions.Authority = String.Format(CultureInfo.InvariantCulture, AzureActiveDirectoryV2Authenticator.Authority, AzureActiveDirectoryV2Authenticator.V2CommonTenant);\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Web.config",
"new_path": "src/NuGetGallery/Web.config",
"diff": "<add key=\"Auth.MicrosoftAccount.ClientSecret\" value=\"\"/>\n<add key=\"Auth.AzureActiveDirectoryV2.Enabled\" value=\"false\"/>\n<add key=\"Auth.AzureActiveDirectoryV2.ClientId\" value=\"\"/>\n- <add key=\"Auth.AzureActiveDirectoryV2.ClientSecret\" value=\"\"/>\n<add key=\"Auth.AzureActiveDirectory.Enabled\" value=\"false\"/>\n<add key=\"Auth.AzureActiveDirectory.ClientId\" value=\"\"/>\n<add key=\"Auth.AzureActiveDirectory.Authority\" value=\"\"/>\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | Remove the client secret from AAD V2 authenticator (#9340)
We were only ever using the id_token which contains enough detail for NuGet.org sign in. The code response is not used.
Progress on https://github.com/NuGet/Engineering/issues/4099 |
455,738 | 10.01.2023 14:59:27 | 21,600 | ced00b48fb091d83469a89b122d9dcd0e975081c | Removes en-us to improve documentation localization | [
{
"change_type": "MODIFY",
"old_path": ".github/ISSUE_TEMPLATE/NUGETORG_ISSUE.yml",
"new_path": ".github/ISSUE_TEMPLATE/NUGETORG_ISSUE.yml",
"diff": "@@ -10,9 +10,9 @@ body:\nThe more detail you provide, the more likely it will be for us to be able to identify what is going on and how to solve it!\n- ### For issues connecting to NuGet.org, please refer to [this guide](https://docs.microsoft.com/en-us/nuget/nuget-org/nuget-org-faq#nuget.org-not-accessible).\n+ ### For issues connecting to NuGet.org, please refer to [this guide](https://docs.microsoft.com/nuget/nuget-org/nuget-org-faq#nuget.org-not-accessible).\n- ### For issues regarding your NuGet.org account, please refer to [this guide](https://docs.microsoft.com/en-us/nuget/nuget-org/nuget-org-faq#nuget.org-account-management).\n+ ### For issues regarding your NuGet.org account, please refer to [this guide](https://docs.microsoft.com/nuget/nuget-org/nuget-org-faq#nuget.org-account-management).\n- type: dropdown\nid: impact\nattributes:\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/App_Code/ViewHelpers.cshtml",
"new_path": "src/NuGetGallery/App_Code/ViewHelpers.cshtml",
"diff": "<p class=\"error-action\">Get me out of here! <a href=\"@url.Home()\">Go home</a></p>\n<p class=\"error-action\">Wondering if NuGet is down? <a href=\"https://status.nuget.org/\">Check our status</a></p>\n<p class=\"error-action\">Looking for a package? <a href=\"@url.PackageList()\">Try searching</a></p>\n- <p class=\"error-action\">Package you're looking for doesn't exist? <a href=\"https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package\">Make one</a></p>\n+ <p class=\"error-action\">Package you're looking for doesn't exist? <a href=\"https://docs.microsoft.com/nuget/quickstart/create-and-publish-a-package\">Make one</a></p>\n<p class=\"error-action\">Pretty sure we messed up? <a href=\"https://github.com/NuGet/NuGetGallery/issues\">File a bug</a></p>\n<p class=\"error-action\">Can't get enough NuGet? <a href=\"https://twitter.com/nuget\">Follow us</a></p>\n</div>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Views/Packages/DisplayPackage.cshtml",
"new_path": "src/NuGetGallery/Views/Packages/DisplayPackage.cshtml",
"diff": "CommandPrefix = \"PM> \",\nInstallPackageCommands = new [] { string.Format(\"NuGet\\\\Install-Package {0} -Version {1}\", Model.Id, Model.Version) },\nAlertLevel = AlertLevel.Info,\n- AlertMessage = \"This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of <a href='https://docs.microsoft.com/en-us/nuget/reference/ps-reference/ps-ref-install-package'>Install-Package</a>.\"\n+ AlertMessage = \"This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of <a href='https://docs.microsoft.com/nuget/reference/ps-reference/ps-ref-install-package'>Install-Package</a>.\"\n},\n: string.Format(\"<PackageReference Include=\\\"{0}\\\" Version=\\\"{1}\\\" />\", Model.Id, Model.Version) },\nAlertLevel = AlertLevel.Info,\nAlertMessage = string.Format(\"For projects that support <a href=\\\"{0}\\\">PackageReference</a>, copy this XML node into the project file to reference the package.\",\n- \"https://docs.microsoft.com/en-us/nuget/consume-packages/package-references-in-project-files\"),\n+ \"https://docs.microsoft.com/nuget/consume-packages/package-references-in-project-files\"),\nCopyLabel = \"Copy the PackageReference XML node\",\n},\[email protected](Url.Absolute(\"~/Content/gallery/img/reserved-indicator-25x25.png\"))\ndata-content=\"@Strings.ReservedNamespace_ReservedIndicatorTooltip\" tabindex=\"0\"\nalt=\"@Strings.ReservedNamespace_ReservedIndicatorTooltip\"/>\n- <a href=\"https://docs.microsoft.com/en-us/nuget/nuget-org/id-prefix-reservation\" class=\"prefix-reserve-label\">\n+ <a href=\"https://docs.microsoft.com/nuget/nuget-org/id-prefix-reservation\" class=\"prefix-reserve-label\">\nPrefix Reserved\n</a>\n</span>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Views/Packages/ReportAbuse.cshtml",
"new_path": "src/NuGetGallery/Views/Packages/ReportAbuse.cshtml",
"diff": "</div>\n<div class=\"reason-error-revenge-porn\" tabindex=\"0\">\n<p>\n- Please report this safety violation through the <a href=\"https://www.microsoft.com/en-us/concern/revengeporn\" title=\"revenge porn portal\">official portal</a>.\n+ Please report this safety violation through the <a href=\"https://www.microsoft.com/concern/revengeporn\" title=\"revenge porn portal\">official portal</a>.\n</p>\n</div>\n<div id=\"report-abuse-form\">\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Views/Pages/Home.cshtml",
"new_path": "src/NuGetGallery/Views/Pages/Home.cshtml",
"diff": "@@ -84,7 +84,7 @@ else if (AskUserToEnable2FA)\n</div>\n<div class=\"row row-gap\">\n<div class=\"col-sm-4\">\n- <a href=\"https://docs.microsoft.com/en-us/nuget/quickstart/use-a-package\"\n+ <a href=\"https://docs.microsoft.com/nuget/quickstart/use-a-package\"\ntitle=\"Learn about how to use NuGet packages\">\n<img width=\"225\" height=\"225\" alt=\"Learn to use packages\"\nsrc=\"~/Content/gallery/img/orange-circle.svg\"\n@@ -108,7 +108,7 @@ else if (AskUserToEnable2FA)\n</p>\n</div>\n<div class=\"col-sm-4\">\n- <a href=\"https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package\"\n+ <a href=\"https://docs.microsoft.com/nuget/quickstart/create-and-publish-a-package\"\ntitle=\"Learn how to create a NuGet package\">\n<img width=\"225\" height=\"225\" alt=\"Learn to create packages\"\nsrc=\"~/Content/gallery/img/blue-circle.svg\"\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Views/Shared/Gallery/Footer.cshtml",
"new_path": "src/NuGetGallery/Views/Shared/Gallery/Footer.cshtml",
"diff": "</div>\n<div class=\"col-sm-4\">\n<span class=\"footer-heading\">\n- <a aria-label=\"Frequently Asked Questions\" href=\"https://docs.microsoft.com/en-us/nuget/policies/nuget-faq\">\n+ <a aria-label=\"Frequently Asked Questions\" href=\"https://docs.microsoft.com/nuget/policies/nuget-faq\">\n<abbr title=\"Frequently Asked Questions\">FAQ</abbr>\n</a>\n</span>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Views/Shared/Gallery/Header.cshtml",
"new_path": "src/NuGetGallery/Views/Shared/Gallery/Header.cshtml",
"diff": "{\n@DisplayNavigationItem(\"Admin\", Url.Admin())\n}\n- @DisplayNavigationItem(\"Documentation\", \"https://docs.microsoft.com/en-us/nuget/\")\n+ @DisplayNavigationItem(\"Documentation\", \"https://docs.microsoft.com/nuget/\")\n@DisplayNavigationItem(\"Downloads\", Url.Downloads())\n@DisplayNavigationItem(\"Blog\", \"https://blog.nuget.org/\")\n</ul>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Views/Shared/_AccountCertificates.cshtml",
"new_path": "src/NuGetGallery/Views/Shared/_AccountCertificates.cshtml",
"diff": "<div class=\"row\" data-bind=\"ifnot: $data && $data.hasCertificates && $data.hasCertificates()\">\n<div class=\"col-xs-12 clearfix\">\n- All your packages need to be signed by one of the registered certificates. <a href=\"https://docs.microsoft.com/en-us/nuget/reference/signed-packages-reference\">Learn more about package signing.</a>\n+ All your packages need to be signed by one of the registered certificates. <a href=\"https://docs.microsoft.com/nuget/reference/signed-packages-reference\">Learn more about package signing.</a>\n<br /> <br />\n</div>\n</div>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Views/Users/ApiKeys.cshtml",
"new_path": "src/NuGetGallery/Views/Users/ApiKeys.cshtml",
"diff": "<br />\n<p>\n<strong>Note:</strong> To push packages to nuget.org you must use <a href=\"https://www.nuget.org/downloads\">nuget.exe v4.1.0 or above</a>,\n- which implements the required <a href=\"https://docs.microsoft.com/en-us/nuget/api/nuget-protocols\">NuGet protocols</a>.\n+ which implements the required <a href=\"https://docs.microsoft.com/nuget/api/nuget-protocols\">NuGet protocols</a>.\n</p>\n</p>\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/NuGetGallery.Facts/Services/PackageMetadataValidationServiceFacts.cs",
"new_path": "tests/NuGetGallery.Facts/Services/PackageMetadataValidationServiceFacts.cs",
"diff": "@@ -1500,8 +1500,8 @@ public async Task WarnsAboutPackagesWithoutReadmeWhenDisplayUploadWarningV2Enabl\nAssert.Null(result.Message);\nvar warning = Assert.Single(result.Warnings);\nAssert.IsType<UploadPackageMissingReadme>(warning);\n- Assert.StartsWith(\"Readme missing. Go to https://learn.microsoft.com/en-us/nuget/create-packages/package-authoring-best-practices#readme learn How to include a readme file within the package.\", warning.PlainTextMessage);\n- Assert.StartsWith(\"<strong>Readme</strong> missing.<a href=\\\"https://learn.microsoft.com/en-us/nuget/create-packages/package-authoring-best-practices#readme\\\"> See how to include a readme file within the package</a>, or add it as you upload.\", warning.RawHtmlMessage);\n+ Assert.StartsWith(\"Readme missing. Go to https://learn.microsoft.com/nuget/create-packages/package-authoring-best-practices#readme learn How to include a readme file within the package.\", warning.PlainTextMessage);\n+ Assert.StartsWith(\"<strong>Readme</strong> missing.<a href=\\\"https://learn.microsoft.com/nuget/create-packages/package-authoring-best-practices#readme\\\"> See how to include a readme file within the package</a>, or add it as you upload.\", warning.RawHtmlMessage);\n}\n[Fact]\n@@ -1527,8 +1527,8 @@ public async Task WarnsAboutPackagesWithoutWhenEmbeddedReadmeNotEnabledAndDispla\nAssert.Null(result.Message);\nvar warning = Assert.Single(result.Warnings);\nAssert.IsType<UploadPackageMissingReadme>(warning);\n- Assert.StartsWith(\"Readme missing. Go to https://learn.microsoft.com/en-us/nuget/create-packages/package-authoring-best-practices#readme learn How to include a readme file within the package.\", warning.PlainTextMessage);\n- Assert.StartsWith(\"<strong>Readme</strong> missing.<a href=\\\"https://learn.microsoft.com/en-us/nuget/create-packages/package-authoring-best-practices#readme\\\"> See how to include a readme file within the package</a>, or add it as you upload.\", warning.RawHtmlMessage);\n+ Assert.StartsWith(\"Readme missing. Go to https://learn.microsoft.com/nuget/create-packages/package-authoring-best-practices#readme learn How to include a readme file within the package.\", warning.PlainTextMessage);\n+ Assert.StartsWith(\"<strong>Readme</strong> missing.<a href=\\\"https://learn.microsoft.com/nuget/create-packages/package-authoring-best-practices#readme\\\"> See how to include a readme file within the package</a>, or add it as you upload.\", warning.RawHtmlMessage);\n}\nprivate async Task<PackageValidationResult> ValidatePackageWithReadme(string readmePath, byte[] readmeFileData)\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | Removes en-us to improve documentation localization (#9325) |
455,784 | 11.01.2023 15:36:42 | 28,800 | b8c3912635ceb31a55ac5234877b4c049a8e4f8c | remove aria-expanded attribute | [
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Scripts/gallery/async-file-upload.js",
"new_path": "src/NuGetGallery/Scripts/gallery/async-file-upload.js",
"diff": "var reportContainerElement = document.createElement(\"div\");\n$(reportContainerElement).attr(\"id\", \"verify-package-block\");\n$(reportContainerElement).attr(\"class\", \"collapse in\");\n- $(reportContainerElement).attr(\"aria-expanded\", \"true\");\n$(reportContainerElement).attr(\"data-bind\", \"template: { name: 'verify-metadata-template', data: data }\");\n$(\"#verify-package-container\").append(reportContainerElement);\nko.applyBindings({ data: model }, reportContainerElement);\nvar submitContainerElement = document.createElement(\"div\");\n$(submitContainerElement).attr(\"id\", \"submit-block\");\n$(submitContainerElement).attr(\"class\", \"collapse in\");\n- $(submitContainerElement).attr(\"aria-expanded\", \"true\");\n$(submitContainerElement).attr(\"data-bind\", \"template: { name: 'submit-package-template', data: data }\");\n$(\"#submit-package-container\").append(submitContainerElement);\nko.applyBindings({ data: model }, submitContainerElement);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Scripts/gallery/page-edit-readme.js",
"new_path": "src/NuGetGallery/Scripts/gallery/page-edit-readme.js",
"diff": "@@ -237,7 +237,6 @@ var BindReadMeDataManager = (function () {\nvar readMeContainerElement = document.createElement(\"div\");\n$(readMeContainerElement).attr(\"id\", \"import-readme-block\");\n$(readMeContainerElement).attr(\"class\", \"collapse in\");\n- $(readMeContainerElement).attr(\"aria-expanded\", \"true\");\n$(readMeContainerElement).attr(\"data-bind\", \"template: { name: 'import-readme-template', data: data }\");\n$(\"#import-readme-container\").append(readMeContainerElement);\nko.applyBindings({ data: model }, readMeContainerElement);\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | remove aria-expanded attribute (#9348) |
455,744 | 26.01.2023 12:38:48 | 28,800 | 92ae5510c9462fa377ae36d99904a691fcfa81bd | More logging for downloads service. | [
{
"change_type": "MODIFY",
"old_path": "src/GitHubVulnerabilities2Db/Gallery/ThrowingTelemetryService.cs",
"new_path": "src/GitHubVulnerabilities2Db/Gallery/ThrowingTelemetryService.cs",
"diff": "@@ -400,5 +400,13 @@ public IDisposable TrackAsyncSqlConnectionCreationDuration()\n{\nthrow new NotImplementedException();\n}\n+\n+ public void TrackDownloadJsonTotalPackageIds(int totalPackageIds) {\n+ throw new NotImplementedException();\n+ }\n+\n+ public void TrackDownloadJsonTotalPackageVersions(int totalPackageVersions) {\n+ throw new NotImplementedException();\n+ }\n}\n}\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery.Services/Telemetry/ITelemetryService.cs",
"new_path": "src/NuGetGallery.Services/Telemetry/ITelemetryService.cs",
"diff": "@@ -18,6 +18,10 @@ public interface ITelemetryService\nvoid TrackDownloadJsonRefreshDuration(TimeSpan duration);\n+ void TrackDownloadJsonTotalPackageIds(int totalPackageIds);\n+\n+ void TrackDownloadJsonTotalPackageVersions(int totalPackageVersions);\n+\nvoid TrackDownloadCountDecreasedDuringRefresh(string packageId, string packageVersion, long oldCount, long newCount);\nvoid TrackPackageDownloadCountDecreasedFromGallery(string packageId, string packageVersion, long galleryCount, long jsonCount);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery.Services/Telemetry/TelemetryService.cs",
"new_path": "src/NuGetGallery.Services/Telemetry/TelemetryService.cs",
"diff": "@@ -39,6 +39,8 @@ public static class Events\npublic const string GalleryDownloadGreaterThanJsonForPackageRegistration = \"GalleryDownloadGreaterThanJsonForPackageRegistration\";\npublic const string GetPackageDownloadCountFailed = \"GetPackageDownloadCountFailed\";\npublic const string GetPackageRegistrationDownloadCountFailed = \"GetPackageRegistrationDownloadCountFailed\";\n+ public const string DownloadJsonTotalPackageIds = \"DownloadJsonTotalPackageIds\";\n+ public const string DownloadJsonTotalPackageVersions = \"DownloadJsonTotalPackageVersions\";\npublic const string UserPackageDeleteCheckedAfterHours = \"UserPackageDeleteCheckedAfterHours\";\npublic const string UserPackageDeleteExecuted = \"UserPackageDeleteExecuted\";\npublic const string UserMultiFactorAuthenticationEnabled = \"UserMultiFactorAuthenticationEnabled\";\n@@ -279,6 +281,16 @@ public void TrackDownloadJsonRefreshDuration(TimeSpan duration)\nTrackMetric(Events.DownloadJsonRefreshDuration, duration.TotalMilliseconds, properties => { });\n}\n+ public void TrackDownloadJsonTotalPackageIds(int totalPackageIds)\n+ {\n+ TrackMetric(Events.DownloadJsonTotalPackageIds, totalPackageIds, properties => { });\n+ }\n+\n+ public void TrackDownloadJsonTotalPackageVersions(int totalPackageVersions)\n+ {\n+ TrackMetric(Events.DownloadJsonTotalPackageVersions, totalPackageVersions, properties => { });\n+ }\n+\npublic void TrackDownloadCountDecreasedDuringRefresh(string packageId, string packageVersion, long oldCount, long newCount)\n{\nTrackMetric(Events.DownloadCountDecreasedDuringRefresh, 1, properties =>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/App_Start/DefaultDependenciesModule.cs",
"new_path": "src/NuGetGallery/App_Start/DefaultDependenciesModule.cs",
"diff": "@@ -778,7 +778,8 @@ private static void RegisterStatisticsServices(ContainerBuilder builder, IGaller\n{\nvar cloudBlobClientFactory = c.ResolveKeyed<Func<ICloudBlobClient>>(BindingKeys.FeatureFlaggedStatisticsKey);\nvar telemetryService = c.Resolve<ITelemetryService>();\n- var downloadCountService = new CloudDownloadCountService(telemetryService, cloudBlobClientFactory);\n+ var downloadCountServiceLogger = c.Resolve<ILogger<CloudDownloadCountService>>();\n+ var downloadCountService = new CloudDownloadCountService(telemetryService, cloudBlobClientFactory, downloadCountServiceLogger);\nvar dlCountInterceptor = new DownloadCountObjectMaterializedInterceptor(downloadCountService, telemetryService);\nObjectMaterializedInterception.AddInterceptor(dlCountInterceptor);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Services/CloudDownloadCountService.cs",
"new_path": "src/NuGetGallery/Services/CloudDownloadCountService.cs",
"diff": "using System.Net;\nusing System.Threading;\nusing System.Threading.Tasks;\n+using Microsoft.Extensions.Logging;\nusing Microsoft.WindowsAzure.Storage;\nusing Microsoft.WindowsAzure.Storage.Blob;\nusing Microsoft.WindowsAzure.Storage.RetryPolicies;\n@@ -29,6 +30,7 @@ public class CloudDownloadCountService : IDownloadCountService\nprivate readonly ITelemetryService _telemetryService;\nprivate readonly Func<ICloudBlobClient> _cloudBlobClientFactory;\n+ private readonly ILogger<CloudDownloadCountService> _logger;\nprivate readonly object _refreshLock = new object();\nprivate bool _isRefreshing;\n@@ -38,10 +40,12 @@ public class CloudDownloadCountService : IDownloadCountService\npublic CloudDownloadCountService(\nITelemetryService telemetryService,\n- Func<ICloudBlobClient> cloudBlobClientFactory)\n+ Func<ICloudBlobClient> cloudBlobClientFactory,\n+ ILogger<CloudDownloadCountService> logger)\n{\n_telemetryService = telemetryService ?? throw new ArgumentNullException(nameof(telemetryService));\n_cloudBlobClientFactory = cloudBlobClientFactory ?? throw new ArgumentNullException(nameof(cloudBlobClientFactory));\n+ _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n}\npublic bool TryGetDownloadCountForPackageRegistration(string id, out long downloadCount)\n@@ -158,6 +162,9 @@ private async Task RefreshCoreAsync()\n{\ntry\n{\n+ int totalIds = 0;\n+ int totalVersions = 0;\n+\n// The data in downloads.v1.json will be an array of Package records - which has Id, Array of Versions and download count.\n// Sample.json : [[\"AutofacContrib.NSubstitute\",[\"2.4.3.700\",406],[\"2.5.0\",137]],[\"Assman.Core\",[\"2.0.7\",138]]....\nusing (var blobStream = await GetBlobStreamAsync())\n@@ -189,6 +196,8 @@ private async Task RefreshCoreAsync()\ncontinue;\n}\n+ ++totalIds;\n+\nvar versions = _downloadCounts.GetOrAdd(\nid,\n_ => new ConcurrentDictionary<string, long>(StringComparer.OrdinalIgnoreCase));\n@@ -199,6 +208,7 @@ private async Task RefreshCoreAsync()\n{\nvar version = token[0].ToString();\nvar downloadCount = token[1].ToObject<long>();\n+ ++totalVersions;\nif (versions.ContainsKey(version) && downloadCount < versions[version])\n{\n@@ -232,6 +242,9 @@ private async Task RefreshCoreAsync()\n}\n}\n}\n+\n+ _telemetryService.TrackDownloadJsonTotalPackageIds(totalIds);\n+ _telemetryService.TrackDownloadJsonTotalPackageVersions(totalVersions);\n}\ncatch (Exception ex)\n{\n@@ -250,6 +263,8 @@ private ISimpleCloudBlob GetBlobReference()\nvar container = blobClient.GetContainerReference(StatsContainerName);\nvar blob = container.GetBlobReference(DownloadCountBlobName);\n+ _logger.LogInformation(\"Cloud download statistics source: {BlobUri}\", blob.Uri);\n+\nreturn blob;\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/VerifyMicrosoftPackage/Fakes/FakeTelemetryService.cs",
"new_path": "src/VerifyMicrosoftPackage/Fakes/FakeTelemetryService.cs",
"diff": "@@ -402,5 +402,13 @@ public IDisposable TrackAsyncSqlConnectionCreationDuration()\n{\nthrow new NotImplementedException();\n}\n+\n+ public void TrackDownloadJsonTotalPackageIds(int totalPackageIds) {\n+ throw new NotImplementedException();\n+ }\n+\n+ public void TrackDownloadJsonTotalPackageVersions(int totalPackageVersions) {\n+ throw new NotImplementedException();\n+ }\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/NuGetGallery.Facts/Services/CloudDownloadCountServiceFacts.cs",
"new_path": "tests/NuGetGallery.Facts/Services/CloudDownloadCountServiceFacts.cs",
"diff": "using System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n+using Microsoft.Extensions.Logging;\nusing Moq;\nusing NuGetGallery.Services;\nusing Xunit;\n@@ -173,7 +174,10 @@ public class TestableCloudDownloadCountService : CloudDownloadCountService\nprivate readonly BaseFacts _baseFacts;\npublic TestableCloudDownloadCountService(BaseFacts baseFacts)\n- : base(baseFacts._telemetryService.Object, () => baseFacts._cloudBlobClientMock.Object)\n+ : base(\n+ baseFacts._telemetryService.Object,\n+ () => baseFacts._cloudBlobClientMock.Object,\n+ Mock.Of<ILogger<CloudDownloadCountService>>())\n{\n_baseFacts = baseFacts;\n}\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | More logging for downloads service. (#9361) |
455,781 | 30.01.2023 15:09:19 | 21,600 | 6f0bd1efd43017f5c0f8abb401d3bed215da9493 | net6.0-windows7 compatibility added. | [
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery.Core/Frameworks/FrameworkCompatibilityService.cs",
"new_path": "src/NuGetGallery.Core/Frameworks/FrameworkCompatibilityService.cs",
"diff": "@@ -61,6 +61,11 @@ public ISet<NuGetFramework> GetCompatibleFrameworks(IEnumerable<NuGetFramework>\n}\n}\n+ matrix.Add(SupportedFrameworks.Net60Windows7,\n+ new HashSet<NuGetFramework>() {\n+ SupportedFrameworks.Net60Windows, SupportedFrameworks.Net60Windows7,\n+ SupportedFrameworks.Net70Windows, SupportedFrameworks.Net70Windows7 });\n+\nreturn matrix;\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery.Core/Frameworks/SupportedFrameworks.cs",
"new_path": "src/NuGetGallery.Core/Frameworks/SupportedFrameworks.cs",
"diff": "@@ -51,6 +51,9 @@ public static class SupportedFrameworks\npublic static readonly NuGetFramework XamarinTvOs = new NuGetFramework(FrameworkIdentifiers.XamarinTVOS, EmptyVersion);\npublic static readonly NuGetFramework XamarinWatchOs = new NuGetFramework(FrameworkIdentifiers.XamarinWatchOS, EmptyVersion);\n+ public static readonly NuGetFramework Net60Windows7 = new NuGetFramework(FrameworkIdentifiers.NetCoreApp, Version6, \"windows\", Version7);\n+ public static readonly NuGetFramework Net70Windows7 = new NuGetFramework(FrameworkIdentifiers.NetCoreApp, Version7, \"windows\", Version7);\n+\npublic static readonly IReadOnlyList<NuGetFramework> AllSupportedNuGetFrameworks;\nstatic SupportedFrameworks()\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/NuGetGallery.Core.Facts/Frameworks/FrameworkCompatibilityServiceFacts.cs",
"new_path": "tests/NuGetGallery.Core.Facts/Frameworks/FrameworkCompatibilityServiceFacts.cs",
"diff": "@@ -96,5 +96,23 @@ public void ValidPackageFrameworksReturnsFrameworksCompatibleForAtLeastOne(param\nAssert.True(isCompatible);\n}\n}\n+\n+ [Theory]\n+ [InlineData(\"net6.0-windows7.0\", \"net6.0-windows\", \"net6.0-windows7.0\", \"net7.0-windows\", \"net7.0-windows7.0\")]\n+ public void WindowsPlatformVersionsShouldContainAllSpecifiedFrameworks(string windowsDefaultVersionFramework, params string[] windowsProjectFrameworks)\n+ {\n+ var packageFramework = NuGetFramework.Parse(windowsDefaultVersionFramework);\n+ var projectFrameworks = new HashSet<NuGetFramework>();\n+\n+ foreach (var frameworkName in windowsProjectFrameworks) {\n+ projectFrameworks.Add(NuGetFramework.Parse(frameworkName));\n+ }\n+\n+ var compatibleFrameworks = _service.GetCompatibleFrameworks(new HashSet<NuGetFramework>() { packageFramework });\n+ Assert.Equal(windowsProjectFrameworks.Length, compatibleFrameworks.Count);\n+\n+ var containsAllCompatibleFrameworks = compatibleFrameworks.All(cf => projectFrameworks.Contains(cf));\n+ Assert.True(containsAllCompatibleFrameworks);\n+ }\n}\n}\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | net6.0-windows7 compatibility added. (#9364) |
455,754 | 07.02.2023 06:33:41 | -36,000 | 3f692c3ca34aafe4668693aed0714dcbf900c082 | AAD account checks on packages for safety reports | [
{
"change_type": "MODIFY",
"old_path": "src/AccountDeleter/EmptyFeatureFlagService.cs",
"new_path": "src/AccountDeleter/EmptyFeatureFlagService.cs",
"diff": "@@ -276,6 +276,11 @@ public bool IsShowReportAbuseSafetyChangesEnabled()\nthrow new NotImplementedException();\n}\n+ public bool IsAllowAadContentSafetyReportsEnabled()\n+ {\n+ throw new NotImplementedException();\n+ }\n+\npublic bool IsTyposquattingEnabled()\n{\nthrow new NotImplementedException();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/GitHubVulnerabilities2Db/Fakes/FakeFeatureFlagService.cs",
"new_path": "src/GitHubVulnerabilities2Db/Fakes/FakeFeatureFlagService.cs",
"diff": "@@ -215,6 +215,11 @@ public bool IsShowReportAbuseSafetyChangesEnabled()\nthrow new NotImplementedException();\n}\n+ public bool IsAllowAadContentSafetyReportsEnabled()\n+ {\n+ throw new NotImplementedException();\n+ }\n+\npublic bool IsPackageDependentsEnabled(User user)\n{\nthrow new NotImplementedException();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery.Core/CredentialTypes.cs",
"new_path": "src/NuGetGallery.Core/CredentialTypes.cs",
"diff": "@@ -104,6 +104,7 @@ public static bool IsApiKey(string type)\n{\nreturn type?.StartsWith(ApiKey.Prefix, StringComparison.OrdinalIgnoreCase) ?? false;\n}\n+\npublic static bool IsMicrosoftAccount(string type)\n{\nreturn type?.Equals(External.MicrosoftAccount, StringComparison.OrdinalIgnoreCase) ?? false;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery.Services/Configuration/FeatureFlagService.cs",
"new_path": "src/NuGetGallery.Services/Configuration/FeatureFlagService.cs",
"diff": "@@ -52,6 +52,7 @@ public class FeatureFlagService : IFeatureFlagService\nprivate const string ImageAllowlistFlightName = GalleryPrefix + \"ImageAllowlist\";\nprivate const string DisplayBannerFlightName = GalleryPrefix + \"Banner\";\nprivate const string ShowReportAbuseSafetyChanges = GalleryPrefix + \"ShowReportAbuseSafetyChanges\";\n+ private const string AllowAadContentSafetyReports = GalleryPrefix + \"AllowAadContentSafetyReports\";\nprivate const string DisplayTargetFrameworkFeatureName = GalleryPrefix + \"DisplayTargetFramework\";\nprivate const string ComputeTargetFrameworkFeatureName = GalleryPrefix + \"ComputeTargetFramework\";\nprivate const string RecentPackagesNoIndexFeatureName = GalleryPrefix + \"RecentPackagesNoIndex\";\n@@ -333,6 +334,11 @@ public bool IsShowReportAbuseSafetyChangesEnabled()\nreturn _client.IsEnabled(ShowReportAbuseSafetyChanges, defaultValue: false);\n}\n+ public bool IsAllowAadContentSafetyReportsEnabled()\n+ {\n+ return _client.IsEnabled(AllowAadContentSafetyReports, defaultValue: false);\n+ }\n+\npublic bool IsMarkdigMdRenderingEnabled()\n{\nreturn _client.IsEnabled(MarkdigMdRenderingFlightName, defaultValue: false);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery.Services/Configuration/IFeatureFlagService.cs",
"new_path": "src/NuGetGallery.Services/Configuration/IFeatureFlagService.cs",
"diff": "@@ -258,6 +258,11 @@ public interface IFeatureFlagService\n/// </summary>\nbool IsShowReportAbuseSafetyChangesEnabled();\n+ /// <summary>\n+ /// Whether online safety categories are available to content owned by at least one AAD-authenticated account\n+ /// </summary>\n+ bool IsAllowAadContentSafetyReportsEnabled();\n+\n/// <summary>\n/// Whether rendering Markdown content to HTML using Markdig is enabled\n/// </summary>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/NuGetGallery/Controllers/PackagesController.cs",
"new_path": "src/NuGetGallery/Controllers/PackagesController.cs",
"diff": "@@ -1385,6 +1385,7 @@ public virtual ActionResult ReportAbuse(string id, string version)\nvar model = new ReportAbuseViewModel\n{\nReasonChoices = _featureFlagService.IsShowReportAbuseSafetyChangesEnabled()\n+ && (_featureFlagService.IsAllowAadContentSafetyReportsEnabled() || PackageHasNoAadOwners(package))\n? ReportAbuseWithSafetyReasons\n: ReportAbuseReasons,\nPackageId = id,\n@@ -2857,6 +2858,38 @@ public virtual async Task<JsonResult> VerifyPackage(VerifyPackageRequest formDat\n}\n}\n+ private static bool PackageHasNoAadOwners(Package package)\n+ {\n+ var owners = package?.PackageRegistration?.Owners;\n+ if (owners == null || !owners.Any()) {\n+ return true;\n+ }\n+\n+ // First check direct owner credentials\n+ if (owners.Any(o => o.Credentials.GetAzureActiveDirectoryCredential() != null))\n+ {\n+ return false;\n+ }\n+\n+ // Check all members of organization owners\n+ var orgOwners = owners.Where(o => o is Organization).Select(o => o as Organization);\n+ foreach (var orgOwner in orgOwners)\n+ {\n+ if (orgOwner.Members == null)\n+ {\n+ continue;\n+ }\n+\n+ if (orgOwner.Members.Any(m => m.Member?.Credentials != null &&\n+ m.Member.Credentials.GetAzureActiveDirectoryCredential() != null))\n+ {\n+ return false;\n+ }\n+ }\n+\n+ return true;\n+ }\n+\nprivate async Task DeleteUploadedFileForUser(User currentUser, Stream uploadedFileStream)\n{\ntry\n"
},
{
"change_type": "MODIFY",
"old_path": "src/VerifyMicrosoftPackage/Fakes/FakeFeatureFlagService.cs",
"new_path": "src/VerifyMicrosoftPackage/Fakes/FakeFeatureFlagService.cs",
"diff": "@@ -103,6 +103,8 @@ public class FakeFeatureFlagService : IFeatureFlagService\npublic bool IsShowReportAbuseSafetyChangesEnabled() => throw new NotImplementedException();\n+ public bool IsAllowAadContentSafetyReportsEnabled() => throw new NotImplementedException();\n+\npublic bool IsMarkdigMdRenderingEnabled() => throw new NotImplementedException();\npublic bool IsMarkdigMdSyntaxHighlightEnabled() => throw new NotImplementedException();\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/NuGetGallery.Facts/Controllers/PackagesControllerFacts.cs",
"new_path": "tests/NuGetGallery.Facts/Controllers/PackagesControllerFacts.cs",
"diff": "using System.Web.Caching;\nusing System.Web.Mvc;\nusing System.Web.Routing;\n+using Autofac.Features.OwnedInstances;\nusing Moq;\nusing NuGet.Packaging;\nusing NuGet.Services.Entities;\n@@ -5387,11 +5388,239 @@ public static IEnumerable<object[]> Owner_Data\n}\n}\n+ public static IEnumerable<object[]> Credential_Data\n+ {\n+ get\n+ {\n+ // Format:\n+ // 1. bool - true -> expecting to see safety categories\n+ // 2. First array is direct credentials (owners)\n+ // 3. Second array is an array of indirect credentials through owner organization members (first array contains credentials of the org itself)\n+\n+ yield return new object[]\n+ {\n+ true, // no owners, we still want to enable safety reporting\n+ null,\n+ null\n+ };\n+\n+ yield return new object[]\n+ {\n+ true,\n+ new object[]\n+ { // owners\n+ new object[] { \"external.MicrosoftAccount\" }\n+ },\n+ null\n+ };\n+\n+ yield return new object[]\n+ {\n+ false,\n+ new object[]\n+ { // owners\n+ new object[] { \"external.AzureActiveDirectory\" }\n+ },\n+ null\n+ };\n+\n+ yield return new object[]\n+ {\n+ false,\n+ new object[]\n+ { // owners\n+ new object[] { \"external.AzureActiveDirectory\" },\n+ new object[] { \"external.MicrosoftAccount\", \"apikey.v1\" }\n+ },\n+ null\n+ };\n+\n+ yield return new object[]\n+ {\n+ false,\n+ new object[]\n+ { // owners\n+ new object[] { \"external.AzureActiveDirectory\", \"external.MicrosoftAccount\" }\n+ },\n+ null\n+ };\n+\n+ yield return new object[]\n+ {\n+ false,\n+ new object[]\n+ { // owners\n+ new object[] { \"external.MicrosoftAccount\" },\n+ new object[] { \"external.AzureActiveDirectory\", \"apikey.v4\" },\n+ new object[] { \"external.MicrosoftAccount\", \"apikey.v4\" }\n+ },\n+ null\n+ };\n+\n+ yield return new object[]\n+ {\n+ true,\n+ new object[]\n+ { // owners\n+ new object [] { \"external.MicrosoftAccount\" }\n+ },\n+ new object[]\n+ { // owner orgs\n+ new object[]\n+ { // members\n+ new object[] { \"external.MicrosoftAccount\" }, // org credentials\n+ new object [] { \"external.MicrosoftAccount\" }\n+ }\n+ },\n+ };\n+\n+ yield return new object[]\n+ {\n+ true,\n+ null,\n+ new object[]\n+ { // owner orgs\n+ new object[]\n+ { // members\n+ new object[] { \"external.MicrosoftAccount\", \"apikey.v4\" }, // org credentials\n+ new object[] { \"external.MicrosoftAccount\" },\n+ new object[] { \"external.MicrosoftAccount\" },\n+ new object[] { \"external.MicrosoftAccount\" }\n+ },\n+ new object[]\n+ { // members\n+ new object[] { \"external.MicrosoftAccount\" }, // org credentials\n+ new object[] { \"external.MicrosoftAccount\", \"apikey.v4\", \"apikey.v4\" }\n+ }\n+ },\n+ };\n+\n+ yield return new object[]\n+ {\n+ false,\n+ null,\n+ new object[]\n+ { // owner orgs\n+ new object[]\n+ { // members\n+ new object[] { \"external.MicrosoftAccount\", \"apikey.v4\" }, // org credentials\n+ new object[] { \"external.MicrosoftAccount\" }\n+ },\n+ new object[]\n+ { // members\n+ new object[] { \"external.MicrosoftAccount\" }, // org credentials\n+ new object[] { \"external.MicrosoftAccount\", \"apikey.v4\", \"apikey.v4\" }\n+ },\n+ new object[]\n+ { // members\n+ new object[] { \"external.MicrosoftAccount\", \"apikey.v4\" }, // org credentials\n+ new object[] { \"external.MicrosoftAccount\", \"apikey.v4\" },\n+ new object[] { \"external.MicrosoftAccount\", \"apikey.v4\" },\n+ new object[] { \"external.AzureActiveDirectory\" }\n+ }\n+ },\n+ };\n+\n+ yield return new object[]\n+ {\n+ true,\n+ new object[]\n+ { // owners\n+ new object[] {\"external.MicrosoftAccount\", \"apikey.v4\" }\n+ },\n+ new object[]\n+ { // owner orgs\n+ new object[]\n+ { // members\n+ new object[] { \"external.MicrosoftAccount\" }, // org credentials\n+ new object[] { \"external.MicrosoftAccount\" }\n+ },\n+ new object[]\n+ { // members\n+ new object[] { \"external.MicrosoftAccount\", \"apikey.v4\" }, // org credentials\n+ new object[] { \"external.MicrosoftAccount\" },\n+ new object[] { \"apikey.v4\", \"external.MicrosoftAccount\", \"apikey.v4\" }\n+ }\n+ },\n+ };\n+\n+ yield return new object[]\n+ {\n+ false,\n+ new object[]\n+ { // owners\n+ new object[] {\"external.MicrosoftAccount\", \"apikey.v4\" }\n+ },\n+ new object[]\n+ { // owner orgs\n+ new object[]\n+ { // members\n+ new object[] { \"apikey.v1\", \"external.MicrosoftAccount\" }, // org credentials\n+ new object[] { \"external.MicrosoftAccount\" }\n+ },\n+ new object[]\n+ { // members\n+ new object[] { \"external.MicrosoftAccount\" }, // org credentials\n+ new object[] { \"external.MicrosoftAccount\", \"apikey.v4\" },\n+ new object[] { \"external.AzureActiveDirectory\", \"apikey.v4\" }\n+ }\n+ },\n+ };\n+\n+ yield return new object[]\n+ {\n+ false,\n+ new object[]\n+ { // owners\n+ new object[] {\"external.MicrosoftAccount\", \"apikey.v4\" }\n+ },\n+ new object[]\n+ { // owner orgs\n+ new object[]\n+ { // members\n+ new object[] { \"external.MicrosoftAccount\" }, // org credentials\n+ new object[] { \"external.MicrosoftAccount\" }\n+ },\n+ new object[]\n+ { // members\n+ new object[] { \"external.AzureActiveDirectory\", \"apikey.v4\" }, // org credentials\n+ new object[] { \"external.MicrosoftAccount\", \"apikey.v4\" },\n+ new object[] { \"external.MicrosoftAccount\", \"apikey.v4\" }\n+ }\n+ },\n+ };\n+\n+ yield return new object[]\n+ {\n+ false,\n+ new object[]\n+ { // owners\n+ new object[] {\"external.MicrosoftAccount\", \"apikey.v4\" }\n+ },\n+ new object[]\n+ { // owner orgs\n+ new object[]\n+ { // members\n+ new object[] { \"external.MicrosoftAccount\" }, // org credentials\n+ new object[] { \"external.MicrosoftAccount\" }\n+ },\n+ new object[] { }, // allow for corner case where an org has no members\n+ new object[]\n+ { // members\n+ new object[] { \"external.MicrosoftAccount\" }, // org credentials\n+ new object[] { \"external.MicrosoftAccount\", \"apikey.v4\" },\n+ new object[] { \"external.AzureActiveDirectory\", \"apikey.v4\" }\n+ }\n+ },\n+ };\n+ }\n+ }\n+\n[Theory]\n[MemberData(nameof(NotOwner_Data))]\npublic void ShowsFormWhenNotOwner(User currentUser, User owner)\n{\n- var result = GetReportAbuseResult(currentUser, owner, out var package);\n+ var result = GetReportAbuseResult(currentUser, owner);\nAssert.IsType<ViewResult>(result);\nvar viewResult = result as ViewResult;\n@@ -5419,7 +5648,7 @@ public void HidesFormForCertainPackages(User currentUser, User owner)\n}\n};\n- var result = GetReportAbuseResultInternal(currentUser, owner, package);\n+ var result = GetReportAbuseResult(currentUser, package);\nAssert.IsType<ViewResult>(result);\nvar viewResult = result as ViewResult;\n@@ -5435,25 +5664,116 @@ public void HidesFormForCertainPackages(User currentUser, User owner)\n[MemberData(nameof(Owner_Data))]\npublic void RedirectsToReportMyPackageWhenOwner(User currentUser, User owner)\n{\n- var result = GetReportAbuseResult(currentUser, owner, out var package);\n+ var result = GetReportAbuseResult(currentUser, owner);\nAssert.IsType<RedirectToRouteResult>(result);\nvar redirectResult = result as RedirectToRouteResult;\nAssert.Equal(\"ReportMyPackage\", redirectResult.RouteValues[\"Action\"]);\n}\n- public ActionResult GetReportAbuseResult(User currentUser, User owner, out Package package)\n+ [Theory]\n+ [MemberData(nameof(Credential_Data))]\n+ public void IncludesSafetyCategoriesWhenNotAadPresent(bool expectingSafetyCategories, object[] directOwnerCredentials, object[] indirectOwnerCredentials)\n+ {\n+ // Arrange\n+ List<User> owners = new List<User>();\n+\n+ // -- Direct owners\n+ if (directOwnerCredentials != null)\n{\n- package = new Package\n+ foreach(var ownerCredentialTypes in directOwnerCredentials)\n+ {\n+ owners.Add(new User\n+ {\n+ Credentials = ((object[])ownerCredentialTypes).Select(ct => new Credential { Type = (string)ct }).ToList()\n+ });\n+ }\n+ }\n+\n+ // -- Organization owners\n+ if (indirectOwnerCredentials != null)\n+ {\n+ foreach (var ownerMembers in indirectOwnerCredentials)\n+ {\n+ var organization = new Organization\n+ {\n+ Members = new List<Membership>()\n+ };\n+\n+ var orgCredentialsDone = false;\n+ foreach(var memberCredentialTypes in (object[])ownerMembers)\n+ {\n+ // the first array in an organization object contains the credentials of the org itself\n+ if (!orgCredentialsDone)\n+ {\n+ organization.Credentials = ((object[])memberCredentialTypes).Select(ct => new Credential { Type = (string)ct }).ToList();\n+ orgCredentialsDone = true;\n+ }\n+ else\n+ {\n+ var membership = new Membership\n+ {\n+ Organization = organization\n+ };\n+\n+ var member = new User\n+ {\n+ Credentials = ((object[])memberCredentialTypes).Select(ct => new Credential { Type = (string)ct }).ToList(),\n+ Organizations = new List<Membership> { membership }\n+ };\n+\n+ membership.Member = member;\n+ organization.Members.Add(membership);\n+ }\n+ }\n+\n+ owners.Add(organization);\n+ }\n+ }\n+\n+ var package = new Package\n+ {\n+ PackageRegistration = new PackageRegistration { Id = PackageId, Owners = owners },\n+ Version = PackageVersion\n+ };\n+\n+ var featureFlagService = new Mock<IFeatureFlagService>();\n+ featureFlagService.Setup(ff => ff.IsShowReportAbuseSafetyChangesEnabled()).Returns(true);\n+ featureFlagService.Setup(ff => ff.IsAllowAadContentSafetyReportsEnabled()).Returns(false);\n+\n+ // Act\n+ var result = GetReportAbuseResult(null, package, featureFlagService);\n+\n+ // Assert\n+ Assert.IsType<ViewResult>(result);\n+ var viewResult = result as ViewResult;\n+\n+ Assert.IsType<ReportAbuseViewModel>(viewResult.Model);\n+ var model = viewResult.Model as ReportAbuseViewModel;\n+\n+ Assert.Equal(expectingSafetyCategories, model.ReasonChoices.Contains(ReportPackageReason.ChildSexualExploitationOrAbuse));\n+ Assert.Equal(expectingSafetyCategories, model.ReasonChoices.Contains(ReportPackageReason.TerrorismOrViolentExtremism));\n+ Assert.Equal(expectingSafetyCategories, model.ReasonChoices.Contains(ReportPackageReason.ImminentHarm));\n+ Assert.Equal(expectingSafetyCategories, model.ReasonChoices.Contains(ReportPackageReason.HateSpeech));\n+ Assert.Equal(expectingSafetyCategories, model.ReasonChoices.Contains(ReportPackageReason.RevengePorn));\n+ Assert.Equal(expectingSafetyCategories, model.ReasonChoices.Contains(ReportPackageReason.OtherNudityOrPornography));\n+ }\n+\n+ private ActionResult GetReportAbuseResult(User currentUser, User owner)\n+ {\n+ var package = new Package\n{\nPackageRegistration = new PackageRegistration { Id = PackageId, Owners = { owner } },\nVersion = PackageVersion\n};\n- return GetReportAbuseResultInternal(currentUser, owner, package);\n+ return GetReportAbuseResult(currentUser, package);\n}\n- private ActionResult GetReportAbuseResultInternal(User currentUser, User owner, Package package)\n+ private ActionResult GetReportAbuseResult(User currentUser, Package package) =>\n+ GetReportAbuseResult(currentUser, package, featureFlagService: null);\n+\n+ private ActionResult GetReportAbuseResult(User currentUser, Package package, Mock<IFeatureFlagService> featureFlagService)\n{\nvar packageService = new Mock<IPackageService>();\npackageService.Setup(p => p.FindPackageByIdAndVersionStrict(PackageId, PackageVersion)).Returns(package);\n@@ -5461,6 +5781,7 @@ private ActionResult GetReportAbuseResultInternal(User currentUser, User owner,\nvar controller = CreateController(\nGetConfigurationService(),\npackageService: packageService,\n+ featureFlagService: featureFlagService,\nhttpContext: httpContext);\ncontroller.SetCurrentUser(currentUser);\nTestUtility.SetupUrlHelper(controller, httpContext);\n"
}
]
| C# | Apache License 2.0 | nuget/nugetgallery | AAD account checks on packages for safety reports (#9360) |
393,978 | 16.03.2017 18:31:31 | 25,200 | 128c1dd9c50641661d3aa74a9187b177b0841f05 | pass ret to definition_helpers in APISpec.definition | [
{
"change_type": "MODIFY",
"old_path": "apispec/core.py",
"new_path": "apispec/core.py",
"diff": "@@ -219,7 +219,7 @@ class APISpec(object):\n# Execute all helpers from plugins\nfor func in self._definition_helpers:\ntry:\n- ret.update(func(self, name, **kwargs))\n+ ret.update(func(self, name, definition=ret, **kwargs))\nexcept TypeError:\ncontinue\nif properties:\n@@ -269,6 +269,8 @@ class APISpec(object):\n- Return a `dict` representation of the definition's Schema object.\nThe helper may define any named arguments after the `name` argument.\n+ In `kwargs`, you will find among other things:\n+ - Definition: the current state of the definition of the schema.\nhttps://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#definitionsObject\n"
}
]
| Python | MIT License | marshmallow-code/apispec | pass ret to definition_helpers in APISpec.definition |
393,978 | 17.03.2017 10:14:41 | 25,200 | 83c4917c9b14edf7b33117f0315cb4f5f202bb1d | edited doc, added test | [
{
"change_type": "MODIFY",
"old_path": "apispec/core.py",
"new_path": "apispec/core.py",
"diff": "@@ -269,8 +269,8 @@ class APISpec(object):\n- Return a `dict` representation of the definition's Schema object.\nThe helper may define any named arguments after the `name` argument.\n- In `kwargs`, you will find among other things:\n- - Definition: the current state of the definition of the schema.\n+ ``kwargs`` will include (among other things):\n+ - definition (dict): current state of the definition\nhttps://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#definitionsObject\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_core.py",
"new_path": "tests/test_core.py",
"diff": "@@ -83,6 +83,20 @@ class TestDefinitions:\ndefs_json = spec.to_dict()['definitions']\nassert defs_json['Pet']['discriminator'] == 'name'\n+ def test_pass_definition_to_plugins(self, spec):\n+ def def_helper(spec, name, **kwargs):\n+ if kwargs.get('definition') is not None:\n+ return {'available': True}\n+\n+ return {'available': False}\n+\n+ spec.register_definition_helper(def_helper)\n+ spec.definition('Pet', properties=self.properties)\n+\n+ defs_json = spec.to_dict()['definitions']\n+\n+ assert defs_json['Pet']['available']\n+\nclass TestPath:\npaths = {\n"
}
]
| Python | MIT License | marshmallow-code/apispec | edited doc, added test |
394,026 | 17.04.2017 13:02:46 | 25,200 | ebb7328e2d1dab2ecdb2de797ba881a64c9003d1 | sort list of reqd fields | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/swagger.py",
"new_path": "apispec/ext/marshmallow/swagger.py",
"diff": "@@ -502,6 +502,8 @@ def fields2jsonschema(fields, schema=None, spec=None, use_refs=True, dump=True,\nif not partial or (is_collection(partial) and field_name not in partial):\njsonschema.setdefault('required', []).append(observed_field_name)\n+ jsonschema.setdefault('required', []).sort()\n+\nif Meta is not None:\nif hasattr(Meta, 'title'):\njsonschema['title'] = Meta.title\n"
}
]
| Python | MIT License | marshmallow-code/apispec | sort list of reqd fields |
394,026 | 17.04.2017 13:28:05 | 25,200 | ca28f03ff83eb5e765cbface3892fc3e1d557a28 | do not add empty required if none already | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/swagger.py",
"new_path": "apispec/ext/marshmallow/swagger.py",
"diff": "@@ -502,7 +502,8 @@ def fields2jsonschema(fields, schema=None, spec=None, use_refs=True, dump=True,\nif not partial or (is_collection(partial) and field_name not in partial):\njsonschema.setdefault('required', []).append(observed_field_name)\n- jsonschema.setdefault('required', []).sort()\n+ if 'required' in jsonschema:\n+ jsonschema['required'].sort()\nif Meta is not None:\nif hasattr(Meta, 'title'):\n"
}
]
| Python | MIT License | marshmallow-code/apispec | do not add empty required if none already |
394,012 | 26.05.2017 16:38:08 | 10,800 | 85077553e2d0a56f2dac04c0410645bac65e5a8f | adding bottle framework support | [
{
"change_type": "MODIFY",
"old_path": ".gitignore",
"new_path": ".gitignore",
"diff": "@@ -33,6 +33,7 @@ nosetests.xml\n.mr.developer.cfg\n.project\n.pydevproject\n+.idea\n# Complexity\noutput/*.html\n"
},
{
"change_type": "MODIFY",
"old_path": "AUTHORS.rst",
"new_path": "AUTHORS.rst",
"diff": "@@ -29,3 +29,4 @@ Contributors (chronological)\n- Matija Besednik `@matijabesednik <https://github.com/matijabesednik>`_\n- Boris Serebrov `@serebrov <https://github.com/serebrov>`_\n- Daniel Radetsky `@dradetsky <https://github.com/dradetsky>`_\n+- Lucas Coutinho`@lucas_rc <https://github.com/lucas_rc>`_\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "apispec/ext/bottle.py",
"diff": "+# -*- coding: utf-8 -*-\n+\"\"\"Bottle plugin. Includes a path helper that allows you to pass an urlspec (path-handler pair)\n+object to `add_path`.\n+::\n+\n+ from bottle import route, default_app\n+\n+ app = default_app()\n+\n+ @route('/gists/<gist_id>')\n+ def gist_detail(gist_id):\n+ '''Gist detail view.\n+ ---\n+ get:\n+ responses:\n+ 200:\n+ schema:\n+ $ref: '#/definitions/Gist'\n+ '''\n+ return 'detail for gist {}'.format(gist_id)\n+\n+ app.test_request_context().push()\n+ spec.add_path(view=gist_detail)\n+ print(spec.to_dict()['paths'])\n+ # {'/gists/{gist_id}': {'get': {'responses': {200: {'schema': {'$ref': '#/definitions/Gist'}}}}}}\n+ from pprint import pprint\n+\n+\n+\"\"\"\n+import re\n+\n+from bottle import default_app\n+\n+from apispec import Path\n+from apispec import utils\n+from apispec.exceptions import APISpecError\n+\n+app = default_app()\n+\n+\n+RE_URL = re.compile(r'<(?:[^:<>]+:)?([^<>]+)>')\n+\n+\n+def bottle_path_to_swagger(path):\n+ return RE_URL.sub(r'{\\1}', path)\n+\n+\n+def _route_for_view(view):\n+ endpoint = None\n+ for route in app.routes:\n+ if route._context['callback'] == view:\n+ endpoint = route\n+ break\n+ if not endpoint:\n+ raise APISpecError('Could not find endpoint for route {0}'.format(view))\n+ return endpoint\n+\n+\n+def path_from_router(spec, view, operations, **kwargs):\n+ operations = utils.load_operations_from_docstring(view.__doc__)\n+ route = _route_for_view(view)\n+ bottle_path = bottle_path_to_swagger(route.rule)\n+ return Path(path=bottle_path, operations=operations)\n+\n+\n+def setup(spec):\n+ \"\"\"Setup for the plugin.\"\"\"\n+ spec.register_path_helper(path_from_router)\n"
},
{
"change_type": "MODIFY",
"old_path": "dev-requirements.txt",
"new_path": "dev-requirements.txt",
"diff": "@@ -8,6 +8,7 @@ flake8==3.0.4\nFlask\nmarshmallow\ntornado\n+bottle\n# testing\npytest>=2.8.0\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tests/test_ext_bottle.py",
"diff": "+# -*- coding: utf-8 -*-\n+import pytest\n+\n+from bottle import route\n+from apispec import APISpec\n+\n+\[email protected]()\n+def spec():\n+ return APISpec(\n+ title='Swagger Petstore',\n+ version='1.0.0',\n+ description='This is a sample Petstore server. You can find out more '\n+ 'about Swagger at <a href=\\\"http://swagger.wordnik.com\\\">http://swagger.wordnik.com</a> '\n+ 'or on irc.freenode.net, #swagger. For this sample, you can use the api '\n+ 'key \\\"special-key\\\" to test the authorization filters',\n+ plugins=[\n+ 'apispec.ext.bottle'\n+ ]\n+ )\n+\n+\n+class TestPathHelpers:\n+\n+ def test_path_from_view(self, spec):\n+ @route('/hello')\n+ def hello():\n+ return 'hi'\n+ spec.add_path(view=hello,\n+ operations={'get': {'parameters': [], 'responses': {'200': '..params..'}}})\n+ assert '/hello' in spec._paths\n+ assert 'get' in spec._paths['/hello']\n+ expected = {'parameters': [], 'responses': {'200': '..params..'}}\n+ assert spec._paths['/hello']['get'] == expected\n+\n+ def test_path_with_multiple_methods(self, spec):\n+\n+ @route('/hello', methods=['GET', 'POST'])\n+ def hello():\n+ return 'hi'\n+\n+ spec.add_path(view=hello, operations=dict(\n+ get={'description': 'get a greeting', 'responses': {'200': '..params..'}},\n+ post={'description': 'post a greeting', 'responses': {'200': '..params..'}}\n+ ))\n+ get_op = spec._paths['/hello']['get']\n+ post_op = spec._paths['/hello']['post']\n+ assert get_op['description'] == 'get a greeting'\n+ assert post_op['description'] == 'post a greeting'\n+\n+ def test_integration_with_docstring_introspection(self, spec):\n+\n+ @route('/hello')\n+ def hello():\n+ \"\"\"A greeting endpoint.\n+\n+ ---\n+ x-extension: value\n+ get:\n+ description: get a greeting\n+ responses:\n+ 200:\n+ description: a pet to be returned\n+ schema:\n+ $ref: #/definitions/Pet\n+\n+ post:\n+ description: post a greeting\n+ responses:\n+ 200:\n+ description:some data\n+\n+ foo:\n+ description: not a valid operation\n+ responses:\n+ 200:\n+ description:\n+ more junk\n+ \"\"\"\n+ return 'hi'\n+\n+ spec.add_path(view=hello)\n+ get_op = spec._paths['/hello']['get']\n+ post_op = spec._paths['/hello']['post']\n+ extension = spec._paths['/hello']['x-extension']\n+ assert get_op['description'] == 'get a greeting'\n+ assert post_op['description'] == 'post a greeting'\n+ assert 'foo' not in spec._paths['/hello']\n+ assert extension == 'value'\n+\n+ def test_path_is_translated_to_swagger_template(self, spec):\n+\n+ @route('/pet/<pet_id>')\n+ def get_pet(pet_id):\n+ return 'representation of pet {pet_id}'.format(pet_id=pet_id)\n+\n+ spec.add_path(view=get_pet)\n+ assert '/pet/{pet_id}' in spec._paths\n+\n+ def test_path_with_params(self, spec):\n+\n+ @route('/pet/<pet_id>/<shop_id>', methods=['POST'])\n+ def set_pet():\n+ return 'new pet!'\n+\n+ spec.add_path(view=set_pet)\n+ assert '/pet/{pet_id}/{shop_id}' in spec._paths\n"
}
]
| Python | MIT License | marshmallow-code/apispec | adding bottle framework support |
394,012 | 30.05.2017 00:57:49 | 10,800 | 575286110844a2a2d9df4aa45d7f28208bdcd095 | minor changes - lint error | [
{
"change_type": "MODIFY",
"old_path": ".gitignore",
"new_path": ".gitignore",
"diff": "@@ -22,6 +22,7 @@ lib64\npip-log.txt\n# Unit test / coverage reports\n+.cache\n.coverage\n.tox\nnosetests.xml\n"
},
{
"change_type": "MODIFY",
"old_path": "apispec/ext/bottle.py",
"new_path": "apispec/ext/bottle.py",
"diff": "\"\"\"Bottle plugin. Includes a path helper that allows you to pass an urlspec (path-handler pair)\nobject to `add_path`.\n::\n-\nfrom bottle import route, default_app\n-\napp = default_app()\n-\n@route('/gists/<gist_id>')\ndef gist_detail(gist_id):\n'''Gist detail view.\n@@ -23,9 +20,6 @@ object to `add_path`.\nspec.add_path(view=gist_detail)\nprint(spec.to_dict()['paths'])\n# {'/gists/{gist_id}': {'get': {'responses': {200: {'schema': {'$ref': '#/definitions/Gist'}}}}}}\n- from pprint import pprint\n-\n-\n\"\"\"\nimport re\n"
}
]
| Python | MIT License | marshmallow-code/apispec | minor changes - lint error |
394,012 | 30.05.2017 17:38:43 | 10,800 | d4dd15ad2f7b438fecc278d876a9de2b9aeaa452 | fix python 2.7 compatibility import | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/bottle.py",
"new_path": "apispec/ext/bottle.py",
"diff": "@@ -21,6 +21,7 @@ object to `add_path`.\nprint(spec.to_dict()['paths'])\n# {'/gists/{gist_id}': {'get': {'responses': {200: {'schema': {'$ref': '#/definitions/Gist'}}}}}}\n\"\"\"\n+from __future__ import absolute_import\nimport re\nfrom bottle import default_app\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_bottle.py",
"new_path": "tests/test_ext_bottle.py",
"diff": "@@ -14,9 +14,9 @@ def spec():\n'about Swagger at <a href=\\\"http://swagger.wordnik.com\\\">http://swagger.wordnik.com</a> '\n'or on irc.freenode.net, #swagger. For this sample, you can use the api '\n'key \\\"special-key\\\" to test the authorization filters',\n- plugins=[\n- 'apispec.ext.bottle'\n- ]\n+ plugins=(\n+ 'apispec.ext.bottle',\n+ )\n)\n"
}
]
| Python | MIT License | marshmallow-code/apispec | fix python 2.7 compatibility import |
394,017 | 06.06.2017 16:02:07 | -36,000 | 57031a1d68be17e9ca9906b29b382c7956220f54 | Correct definition to match output in document.
Code was malformed, with un-even brackets and output was not matching. | [
{
"change_type": "MODIFY",
"old_path": "docs/quickstart.rst",
"new_path": "docs/quickstart.rst",
"diff": "@@ -26,7 +26,7 @@ Add definitions to your spec using `definition <apispec.APISpec.definition>`.\nspec.definition('Gist', properties={\n'id': {'type': 'integer', 'format': 'int64'},\n- 'content': 'type': 'string'},\n+ 'name': {'type': 'string'}\n})\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Correct definition to match output in document.
Code was malformed, with un-even brackets and output was not matching. |
394,018 | 23.06.2017 15:55:40 | -7,200 | 5806528b8a1dda158a70b57d166f50be73bc6479 | correctly fill default parameter if default is boolean False | [
{
"change_type": "MODIFY",
"old_path": "AUTHORS.rst",
"new_path": "AUTHORS.rst",
"diff": "@@ -31,3 +31,4 @@ Contributors (chronological)\n- Daniel Radetsky `@dradetsky <https://github.com/dradetsky>`_\n- Lucas Coutinho `@lucasrc <https://github.com/lucasrc>`_\n- `@lamiskin <https://github.com/lamiskin>`_\n+- Florian Scheffler `@nebularazer <https://github.com/nebularazer>`_\n"
},
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/swagger.py",
"new_path": "apispec/ext/marshmallow/swagger.py",
"diff": "@@ -12,7 +12,7 @@ from collections import OrderedDict\nimport copy\nimport marshmallow\n-from marshmallow.utils import is_collection\n+from marshmallow.utils import is_collection, _Missing\nfrom marshmallow.compat import text_type, binary_type, iteritems\nfrom marshmallow.orderedset import OrderedSet\n@@ -231,7 +231,7 @@ def field2property(field, spec=None, use_refs=True, dump=True, name=None):\nret['format'] = fmt\ndefault = field.default if dump else field.missing\n- if default:\n+ if not isinstance(default, _Missing):\nret['default'] = default\nchoices = field2choices(field)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_swagger.py",
"new_path": "tests/test_swagger.py",
"diff": "@@ -70,11 +70,21 @@ class TestMarshmallowFieldToSwagger:\nres = swagger.field2property(field)\nassert res['default'] == 'foo'\n+ def test_field_with_boolean_false_default(self):\n+ field = fields.Boolean(default=False, missing=None)\n+ res = swagger.field2property(field)\n+ assert res['default'] is False\n+\ndef test_field_with_default_load(self):\nfield = fields.Str(default='foo', missing='bar')\nres = swagger.field2property(field, dump=False)\nassert res['default'] == 'bar'\n+ def test_field_with_boolean_false_default_load(self):\n+ field = fields.Boolean(default=None, missing=False)\n+ res = swagger.field2property(field, dump=False)\n+ assert res['default'] is False\n+\ndef test_fields_with_default_load(self):\nfield_dict = {'field': fields.Str(default='foo', missing='bar')}\nres = swagger.fields2parameters(field_dict, default_in='query')\n"
}
]
| Python | MIT License | marshmallow-code/apispec | correctly fill default parameter if default is boolean False |
394,001 | 09.07.2017 21:06:22 | -32,400 | af462f94f503c02f2702d040f22e609239a5c6cc | Generate parameters specification by marshmallow schema
Implement the proposal in
* generate single entry by "in: body"
* generate array of primitive types otherwise | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/__init__.py",
"new_path": "apispec/ext/marshmallow/__init__.py",
"diff": "@@ -126,12 +126,27 @@ def schema_path_helper(spec, view, **kwargs):\nreturn\noperations = operations.copy()\nfor operation in operations.values():\n+ if 'parameters' in operation:\n+ operation['parameters'] = resolve_parameters(operation['parameters'])\nfor response in operation.get('responses', {}).values():\nif 'schema' in response:\nresponse['schema'] = resolve_schema_dict(spec, response['schema'])\nreturn Path(operations=operations)\n+def resolve_parameters(parameters):\n+ resolved = []\n+ for parameter in parameters:\n+ if not isinstance(parameter.get('schema', {}), dict):\n+ schema_cls = resolve_schema_cls(parameter['schema'])\n+ if issubclass(schema_cls, marshmallow.Schema) and 'in' in parameter:\n+ resolved += swagger.schema2parameters(\n+ schema_cls, default_in=parameter['in'])\n+ continue\n+ resolved.append(parameter)\n+ return resolved\n+\n+\ndef resolve_schema_dict(spec, schema, dump=True):\nif isinstance(schema, dict):\nif (schema.get('type') == 'array' and 'items' in schema):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_marshmallow.py",
"new_path": "tests/test_ext_marshmallow.py",
"diff": "@@ -87,6 +87,37 @@ class TestOperationHelper:\nassert post['responses'][201]['schema'] == swagger.schema2jsonschema(PetSchema)\nassert post['responses'][201]['description'] == 'successful operation'\n+ def test_schema_in_docstring_expand_parameters(self, spec):\n+\n+ def pet_view():\n+ \"\"\"Not much to see here.\n+\n+ ---\n+ get:\n+ parameters:\n+ - in: query\n+ schema: tests.schemas.PetSchema\n+ post:\n+ parameters:\n+ - in: body\n+ schema: tests.schemas.PetSchema\n+ responses:\n+ 200:\n+ schema: tests.schemas.PetSchema\n+ description: successful operation\n+ \"\"\"\n+ return '...'\n+\n+ spec.add_path(path='/pet', view=pet_view)\n+ p = spec._paths['/pet']\n+ assert 'get' in p\n+ get = p['get']\n+ assert 'parameters' in get\n+ assert get['parameters'] == swagger.schema2parameters(PetSchema, default_in='query')\n+ post = p['post']\n+ assert 'parameters' in post\n+ assert post['parameters'] == swagger.schema2parameters(PetSchema, default_in='body')\n+\ndef test_schema_in_docstring_uses_ref_if_available(self, spec):\nspec.definition('Pet', schema=PetSchema)\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Generate parameters specification by marshmallow schema
Implement the proposal in
https://github.com/marshmallow-code/apispec/issues/127
* generate single entry by "in: body"
* generate array of primitive types otherwise |
394,001 | 09.07.2017 22:56:44 | -32,400 | dd2e6f0dd3b3e4d4f7213c18652ccd4e67a68c1a | Remove unused input for test_schema_in_docstring_expand_parameters | [
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_marshmallow.py",
"new_path": "tests/test_ext_marshmallow.py",
"diff": "@@ -101,10 +101,6 @@ class TestOperationHelper:\nparameters:\n- in: body\nschema: tests.schemas.PetSchema\n- responses:\n- 200:\n- schema: tests.schemas.PetSchema\n- description: successful operation\n\"\"\"\nreturn '...'\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Remove unused input for test_schema_in_docstring_expand_parameters |
394,001 | 09.07.2017 23:03:30 | -32,400 | fa9de714109f2d776a2714efb923df4411efa4d3 | Add example of parameters with schema | [
{
"change_type": "MODIFY",
"old_path": "docs/using_plugins.rst",
"new_path": "docs/using_plugins.rst",
"diff": "@@ -68,6 +68,9 @@ Our application will have a marshmallow `Schema <marshmallow.Schema>` for gists.\nfrom marshmallow import Schema, fields\n+ class GistParameter(Schema):\n+ gist_id = fields.Int()\n+\nclass GistSchema(Schema):\nid = fields.Int()\ncontent = fields.Str()\n@@ -116,6 +119,9 @@ We'll add some YAML in the docstring to add response information.\n\"\"\"Gist detail view.\n---\nget:\n+ parameters:\n+ - in: path\n+ schema: GistParameter\nresponses:\n200:\nschema: GistSchema\n@@ -148,7 +154,12 @@ Our OpenAPI spec now looks like this:\n# 'title': 'Gisty',\n# 'version': '1.0.0'},\n# 'parameters': {},\n- # 'paths': {'/gists/{gist_id}': {'get': {'responses': {200: {'schema': {'$ref': '#/definitions/Gist'}}}}}},\n+ # 'paths': {'/gists/{gist_id}': {'get': {'parameters': [{'format': 'int32',\n+ # 'in': 'path',\n+ # 'name': 'gist_id',\n+ # 'required': True,\n+ # 'type': 'integer'}],\n+ # 'responses': {200: {'schema': {'$ref': '#/definitions/Gist'}}}}}},\n# 'swagger': '2.0',\n# 'tags': []}\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Add example of parameters with schema |
393,986 | 10.07.2017 23:00:41 | 21,600 | 6592c8de2ab0e67b4dc7317dd1369ea04b868157 | Add support for Flask MethodView to apispec.ext.flask
Addresses issues and | [
{
"change_type": "MODIFY",
"old_path": "AUTHORS.rst",
"new_path": "AUTHORS.rst",
"diff": "@@ -32,3 +32,4 @@ Contributors (chronological)\n- Lucas Coutinho `@lucasrc <https://github.com/lucasrc>`_\n- `@lamiskin <https://github.com/lamiskin>`_\n- Florian Scheffler `@nebularazer <https://github.com/nebularazer>`_\n+- Douglas Anderson `@djanderson <https://github.com/djanderson>`_\n"
},
{
"change_type": "MODIFY",
"old_path": "apispec/ext/flask.py",
"new_path": "apispec/ext/flask.py",
"diff": "# -*- coding: utf-8 -*-\n-\"\"\"Flask plugin. Includes a path helper that allows you to pass a view\n+\"\"\"Flask plugin. Includes path helpers that allow you to pass a view\nfunction to `add_path`. Inspects URL rules and view docstrings.\n-::\n+\n+Passing a view function::\nfrom flask import Flask\n@@ -23,6 +24,31 @@ function to `add_path`. Inspects URL rules and view docstrings.\nspec.add_path(view=gist_detail)\nprint(spec.to_dict()['paths'])\n# {'/gists/{gist_id}': {'get': {'responses': {200: {'schema': {'$ref': '#/definitions/Gist'}}}}}}\n+\n+Passing a method view function::\n+\n+ from flask import Flask\n+ from flask.views import MethodView\n+\n+ app = Flask(__name__)\n+\n+ class GistApi(MethodView):\n+ def get(self):\n+ '''Gist view\n+ ---\n+ responses:\n+ 200:\n+ schema:\n+ $ref: '#/definitions/Gist'\n+ '''\n+\n+ app.test_request_context().push()\n+ method_view = GistApi.as_view('gists')\n+ app.add_url_rule(\"/gists\", view_func=method_view)\n+ spec.add_path(method_view=method_view)\n+ print(spec.to_dict()['paths'])\n+ # {'/gists', {'get': {'responses': {200: {'schema': {'$ref': '#/definitions/Gist'}}}}}}\n+\n\"\"\"\nfrom __future__ import absolute_import\nimport re\n@@ -72,6 +98,22 @@ def path_from_view(spec, view, **kwargs):\npath = Path(path=path, operations=operations)\nreturn path\n+def path_from_method_view(spec, method_view, **kwargs):\n+ \"\"\"Path helper that allows passing a Flask MethodView view function.\"\"\"\n+ rule = _rule_for_view(method_view)\n+ path = flaskpath2swagger(rule.rule)\n+ app_root = current_app.config['APPLICATION_ROOT'] or '/'\n+ path = urljoin(app_root.rstrip('/') + '/', path.lstrip('/'))\n+ operations = {}\n+ for method in method_view.methods:\n+ method_name = method.lower()\n+ view = getattr(method_view.view_class, method_name)\n+ docstring_yaml = utils.load_yaml_from_docstring(view.__doc__)\n+ operations[method_name] = docstring_yaml or dict()\n+\n+ return Path(path=path, operations=operations or None)\n+\ndef setup(spec):\n\"\"\"Setup for the plugin.\"\"\"\nspec.register_path_helper(path_from_view)\n+ spec.register_path_helper(path_from_method_view)\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/using_plugins.rst",
"new_path": "docs/using_plugins.rst",
"diff": "@@ -152,6 +152,37 @@ Our OpenAPI spec now looks like this:\n# 'swagger': '2.0',\n# 'tags': []}\n+If your API uses `method-based dispatching <http://flask.pocoo.org/docs/0.12/views/#method-based-dispatching>`_, the process is similar. Note that the method no longer needs to be included in the docstring, and that we add the path as a `method_view`.\n+\n+.. code-block:: python\n+\n+ from flask.views import MethodView\n+\n+ class GistApi(MethodView):\n+ def get(self):\n+ '''Gist view\n+ ---\n+ description: get a gist\n+ responses:\n+ 200:\n+ schema:\n+ $ref: '#/definitions/Gist'\n+ '''\n+ pass\n+\n+ def post(self):\n+ pass\n+\n+ app.test_request_context().push()\n+ method_view = GistApi.as_view('gist')\n+ app.add_url_rule(\"/gist\", view_func=method_view)\n+ spec.add_path(method_view=method_view)\n+ print(spec.to_dict()['paths'])\n+ # {'/gist': {'get': {'description': 'get a gist',\n+ # 'responses': {200: {'schema': {'$ref': '#/definitions/Gist'}}}},\n+ # 'post': {}}}\n+ #\n+\nNext Steps\n----------\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_flask.py",
"new_path": "tests/test_ext_flask.py",
"diff": "import pytest\nfrom flask import Flask\n+from flask.views import MethodView\nfrom apispec import APISpec\[email protected]()\n@@ -42,6 +43,31 @@ class TestPathHelpers:\nexpected = {'parameters': [], 'responses': {'200': '..params..'}}\nassert spec._paths['/hello']['get'] == expected\n+ def test_path_from_method_view(self, app, spec):\n+ class HelloApi(MethodView):\n+ def get(self):\n+ \"\"\"A greeting endpoint.\n+ ---\n+ description: get a greeting\n+ responses:\n+ 200:\n+ description: said hi\n+ \"\"\"\n+ return 'hi'\n+\n+ def post(self):\n+ return 'hi'\n+\n+ method_view = HelloApi.as_view('hi')\n+ app.add_url_rule(\"/hi\", view_func=method_view, methods=('GET', 'POST'))\n+ spec.add_path(method_view=method_view)\n+ assert '/hi' in spec._paths\n+ assert 'get' in spec._paths['/hi']\n+ expected = {'description': 'get a greeting',\n+ 'responses': {200: {'description': 'said hi'}}}\n+ assert spec._paths['/hi']['get'] == expected\n+ assert spec._paths['/hi']['post'] == {}\n+\ndef test_path_with_multiple_methods(self, app, spec):\[email protected]('/hello', methods=['GET', 'POST'])\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Add support for Flask MethodView to apispec.ext.flask
Addresses issues #85 and #125. |
394,005 | 29.06.2017 15:45:17 | -10,800 | eea26fb586a078ad5f1bedb7bdaf8486e8be5218 | Allow default value for fields to be callable. | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/swagger.py",
"new_path": "apispec/ext/marshmallow/swagger.py",
"diff": "@@ -232,6 +232,9 @@ def field2property(field, spec=None, use_refs=True, dump=True, name=None):\ndefault = field.default if dump else field.missing\nif default is not marshmallow.missing:\n+ if callable(default):\n+ ret['default'] = default()\n+ else:\nret['default'] = default\nchoices = field2choices(field)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/schemas.py",
"new_path": "tests/schemas.py",
"diff": "@@ -42,3 +42,7 @@ class OrderedSchema(Schema):\nclass Meta:\nordered = True\n+\n+\n+class DefaultCallableSchema(Schema):\n+ numbers = fields.List(fields.Int, default=list)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_marshmallow.py",
"new_path": "tests/test_ext_marshmallow.py",
"diff": "@@ -5,7 +5,7 @@ import json\nfrom apispec import APISpec\nfrom apispec.ext.marshmallow import swagger\nfrom .schemas import PetSchema, AnalysisSchema, SampleSchema, RunSchema, SelfReferencingSchema,\\\n- OrderedSchema, PatternedObjectSchema\n+ OrderedSchema, PatternedObjectSchema, DefaultCallableSchema\[email protected]()\n@@ -200,3 +200,10 @@ class TestFieldWithCustomProps:\nresult = spec._definitions['PatternedObject']['properties']['count2']\nassert 'x-count2' in result\nassert result['x-count2'] == 2\n+\n+\n+class TestDefaultCanBeCallable:\n+ def test_default_can_be_callable(self, spec):\n+ spec.definition('DefaultCallableSchema', schema=DefaultCallableSchema)\n+ result = spec._definitions['DefaultCallableSchema']['properties']['numbers']\n+ assert result['default'] == []\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Allow default value for fields to be callable. |
394,001 | 15.07.2017 00:51:53 | -32,400 | fdd97dd9b97677dca86e3db5de307fec02348e7b | use operations obtained by preceding extension in ext.marshmallow | [
{
"change_type": "MODIFY",
"old_path": "apispec/core.py",
"new_path": "apispec/core.py",
"diff": "@@ -182,6 +182,7 @@ class APISpec(object):\nif isinstance(ret, Path):\nret.path = normalize_path(ret.path)\npath.update(ret)\n+ operations = ret.operations\nif not path.path:\nraise APISpecError('Path template is not specified')\n"
},
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/__init__.py",
"new_path": "apispec/ext/marshmallow/__init__.py",
"diff": "@@ -57,7 +57,7 @@ def schema_definition_helper(spec, name, schema, **kwargs):\nreturn swagger.schema2jsonschema(schema_instance, spec=spec, name=name)\n-def schema_path_helper(spec, view, **kwargs):\n+def schema_path_helper(spec, view=None, **kwargs):\n\"\"\"Path helper that allows passing a Schema as a response. Responses can be\ndefined in a view's docstring.\n::\n@@ -119,8 +119,8 @@ def schema_path_helper(spec, view, **kwargs):\n\"\"\"\noperations = (\n- load_operations_from_docstring(view.__doc__) or\n- kwargs.get('operations')\n+ kwargs.get('operations') or\n+ (view and load_operations_from_docstring(view.__doc__))\n)\nif not operations:\nreturn\n"
}
]
| Python | MIT License | marshmallow-code/apispec | use operations obtained by preceding extension in ext.marshmallow |
394,001 | 18.07.2017 11:59:56 | -32,400 | 802d5f2713e76e6ded2819a0e6bb13c385271067 | use ref in parameters if available | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/__init__.py",
"new_path": "apispec/ext/marshmallow/__init__.py",
"diff": "@@ -127,21 +127,21 @@ def schema_path_helper(spec, view, **kwargs):\noperations = operations.copy()\nfor operation in operations.values():\nif 'parameters' in operation:\n- operation['parameters'] = resolve_parameters(operation['parameters'])\n+ operation['parameters'] = resolve_parameters(spec, operation['parameters'])\nfor response in operation.get('responses', {}).values():\nif 'schema' in response:\nresponse['schema'] = resolve_schema_dict(spec, response['schema'])\nreturn Path(operations=operations)\n-def resolve_parameters(parameters):\n+def resolve_parameters(spec, parameters):\nresolved = []\nfor parameter in parameters:\nif not isinstance(parameter.get('schema', {}), dict):\nschema_cls = resolve_schema_cls(parameter['schema'])\nif issubclass(schema_cls, marshmallow.Schema) and 'in' in parameter:\nresolved += swagger.schema2parameters(\n- schema_cls, default_in=parameter['in'])\n+ schema_cls, default_in=parameter['in'], spec=spec)\ncontinue\nresolved.append(parameter)\nreturn resolved\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_marshmallow.py",
"new_path": "tests/test_ext_marshmallow.py",
"diff": "@@ -135,6 +135,36 @@ class TestOperationHelper:\nassert 'responses' in op\nassert op['responses'][200]['schema']['$ref'] == '#/definitions/Pet'\n+ def test_schema_in_docstring_uses_ref_in_parameters_if_available(self, spec):\n+ spec.definition('Pet', schema=PetSchema)\n+\n+ def pet_view():\n+ \"\"\"Not much to see here.\n+\n+ ---\n+ get:\n+ parameters:\n+ - in: query\n+ schema: tests.schemas.PetSchema\n+ post:\n+ parameters:\n+ - in: body\n+ schema: tests.schemas.PetSchema\n+ \"\"\"\n+ return '...'\n+\n+ spec.add_path(path='/pet', view=pet_view)\n+ p = spec._paths['/pet']\n+ assert 'get' in p\n+ get = p['get']\n+ assert 'parameters' in get\n+ for parameter in get['parameters']:\n+ assert 'schema' not in parameter\n+ post = p['post']\n+ assert 'parameters' in post\n+ assert len(post['parameters']) == 1\n+ assert post['parameters'][0]['schema']['$ref'] == '#/definitions/Pet'\n+\ndef test_schema_array_in_docstring_uses_ref_if_available(self, spec):\nspec.definition('Pet', schema=PetSchema)\n"
}
]
| Python | MIT License | marshmallow-code/apispec | use ref in parameters if available |
394,001 | 02.08.2017 18:38:26 | -32,400 | 33b054ca72d1a5e21fa59176f3778439b05e9556 | integrate path_helper function for method_view into path_from_view | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/flask.py",
"new_path": "apispec/ext/flask.py",
"diff": "@@ -55,7 +55,7 @@ Passing a method view function::\napp.test_request_context().push()\nmethod_view = GistApi.as_view('gists')\napp.add_url_rule(\"/gists\", view_func=method_view)\n- spec.add_path(method_view=method_view)\n+ spec.add_path(view=method_view)\nprint(spec.to_dict()['paths'])\n# {'/gists': {'get': {'responses': {200: {'schema': {'$ref': '#/definitions/Gist'}}}},\n# 'post': {},\n@@ -72,6 +72,7 @@ except ImportError:\nfrom urlparse import urljoin\nfrom flask import current_app\n+from flask.views import MethodView\nfrom apispec.compat import iteritems\nfrom apispec import Path\n@@ -109,22 +110,16 @@ def path_from_view(spec, view, **kwargs):\npath = urljoin(app_root.rstrip('/') + '/', path.lstrip('/'))\noperations = utils.load_operations_from_docstring(view.__doc__)\npath = Path(path=path, operations=operations)\n- return path\n-\n-def path_from_method_view(spec, method_view, **kwargs):\n- \"\"\"Path helper that allows passing a Flask MethodView view function.\"\"\"\n- path = path_from_view(spec, method_view)\n+ if hasattr(view, 'view_class') and issubclass(view.view_class, MethodView):\noperations = {}\n- for method in method_view.methods:\n+ for method in view.methods:\nmethod_name = method.lower()\n- view = getattr(method_view.view_class, method_name)\n- docstring_yaml = utils.load_yaml_from_docstring(view.__doc__)\n+ method = getattr(view.view_class, method_name)\n+ docstring_yaml = utils.load_yaml_from_docstring(method.__doc__)\noperations[method_name] = docstring_yaml or dict()\n-\npath.operations.update(operations)\nreturn path\ndef setup(spec):\n\"\"\"Setup for the plugin.\"\"\"\nspec.register_path_helper(path_from_view)\n- spec.register_path_helper(path_from_method_view)\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/using_plugins.rst",
"new_path": "docs/using_plugins.rst",
"diff": "@@ -152,7 +152,7 @@ Our OpenAPI spec now looks like this:\n# 'swagger': '2.0',\n# 'tags': []}\n-If your API uses `method-based dispatching <http://flask.pocoo.org/docs/0.12/views/#method-based-dispatching>`_, the process is similar. Note that the method no longer needs to be included in the docstring, and that we add the path as a `method_view`.\n+If your API uses `method-based dispatching <http://flask.pocoo.org/docs/0.12/views/#method-based-dispatching>`_, the process is similar. Note that the method no longer needs to be included in the docstring.\n.. code-block:: python\n@@ -176,7 +176,7 @@ If your API uses `method-based dispatching <http://flask.pocoo.org/docs/0.12/vie\napp.test_request_context().push()\nmethod_view = GistApi.as_view('gist')\napp.add_url_rule(\"/gist\", view_func=method_view)\n- spec.add_path(method_view=method_view)\n+ spec.add_path(view=method_view)\nprint(spec.to_dict()['paths'])\n# {'/gist': {'get': {'description': 'get a gist',\n# 'responses': {200: {'schema': {'$ref': '#/definitions/Gist'}}}},\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_flask.py",
"new_path": "tests/test_ext_flask.py",
"diff": "@@ -64,7 +64,7 @@ class TestPathHelpers:\nmethod_view = HelloApi.as_view('hi')\napp.add_url_rule(\"/hi\", view_func=method_view, methods=('GET', 'POST'))\n- spec.add_path(method_view=method_view)\n+ spec.add_path(view=method_view)\nexpected = {'description': 'get a greeting',\n'responses': {200: {'description': 'said hi'}}}\nassert spec._paths['/hi']['get'] == expected\n"
}
]
| Python | MIT License | marshmallow-code/apispec | integrate path_helper function for method_view into path_from_view |
394,001 | 02.08.2017 18:45:45 | -32,400 | 217ce4cd68fbabce046e752e237b567ed8e0eaaa | path helper functions are integrated to the one | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/flask.py",
"new_path": "apispec/ext/flask.py",
"diff": "# -*- coding: utf-8 -*-\n-\"\"\"Flask plugin. Includes path helpers that allow you to pass a view\n+\"\"\"Flask plugin. Includes a path helper that allows you to pass a view\nfunction to `add_path`. Inspects URL rules and view docstrings.\nPassing a view function::\n"
}
]
| Python | MIT License | marshmallow-code/apispec | path helper functions are integrated to the one |
394,033 | 08.08.2017 17:14:23 | -10,800 | b5e93a9b26268a8f3ceadef8491c15335c2452fc | Fix swagger location mapping for default_in param in property2parameter | [
{
"change_type": "MODIFY",
"old_path": "AUTHORS.rst",
"new_path": "AUTHORS.rst",
"diff": "@@ -35,3 +35,4 @@ Contributors (chronological)\n- Vadim Radovel `@NightBlues <https://github.com/NightBlues>`_\n- Yoichi NAKAYAMA `@yoichi <https://github.com/yoichi>`_\n- Douglas Anderson `@djanderson <https://github.com/djanderson>`_\n+- Marat Sharafutdinov `@decaz <https://github.com/decaz>`_\n"
},
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/swagger.py",
"new_path": "apispec/ext/marshmallow/swagger.py",
"diff": "@@ -400,7 +400,8 @@ def property2parameter(prop, name='body', required=False, multiple=False, locati\n:raise: TranslationError if arg object cannot be translated to a Parameter Object schema.\n:rtype: dict, a Parameter Object\n\"\"\"\n- swagger_location = __location_map__.get(location, default_in)\n+ swagger_default_in = __location_map__.get(default_in, default_in)\n+ swagger_location = __location_map__.get(location, swagger_default_in)\nret = {\n'in': swagger_location,\n'required': required,\n@@ -527,6 +528,7 @@ __location_map__ = {\n'querystring': 'query',\n'json': 'body',\n'headers': 'header',\n+ 'cookies': 'cookie',\n'form': 'formData',\n'files': 'formData',\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_swagger.py",
"new_path": "tests/test_swagger.py",
"diff": "@@ -103,6 +103,16 @@ class TestMarshmallowFieldToSwagger:\nres = swagger.fields2parameters(field_dict, default_in='headers')\nassert res[0]['in'] == 'query'\n+ def test_fields_location_mapping(self):\n+ field_dict = {'field': fields.Str(location='cookies')}\n+ res = swagger.fields2parameters(field_dict, default_in='headers')\n+ assert res[0]['in'] == 'cookie'\n+\n+ def test_fields_default_location_mapping(self):\n+ field_dict = {'field': fields.Str()}\n+ res = swagger.fields2parameters(field_dict, default_in='headers')\n+ assert res[0]['in'] == 'header'\n+\ndef test_fields_with_dump_only(self):\nclass UserSchema(Schema):\nname = fields.Str(dump_only=True)\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Fix swagger location mapping for default_in param in property2parameter |
394,026 | 03.08.2017 19:08:27 | 25,200 | 57b7029775349accca432c9af442d90622e67713 | simple decorator test | [
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_marshmallow.py",
"new_path": "tests/test_ext_marshmallow.py",
"diff": "import pytest\nimport json\n+from marshmallow.fields import Field, DateTime\n+\nfrom apispec import APISpec\nfrom apispec.ext.marshmallow import swagger\nfrom .schemas import PetSchema, AnalysisSchema, SampleSchema, RunSchema, SelfReferencingSchema,\\\n@@ -33,6 +35,42 @@ class TestDefinitionHelper:\nassert props['id']['type'] == 'integer'\nassert props['name']['type'] == 'string'\n+\n+class TestCustomField:\n+\n+ def test_can_use_custom_field_decorator(self, spec):\n+\n+ @swagger.map_to_swagger_field(DateTime)\n+ class CustomNameA(Field):\n+ pass\n+\n+ @swagger.map_to_swagger_field('integer', 'int32')\n+ class CustomNameB(Field):\n+ pass\n+\n+ class CustomPetASchema(PetSchema):\n+ name = CustomNameA()\n+\n+ class CustomPetBSchema(PetSchema):\n+ name = CustomNameB()\n+\n+ spec.definition('Pet', schema=PetSchema)\n+ spec.definition('CustomPetA', schema=CustomPetASchema)\n+ spec.definition('CustomPetB', schema=CustomPetBSchema)\n+\n+ props_0 = spec._definitions['Pet']['properties']\n+ props_a = spec._definitions['CustomPetA']['properties']\n+ props_b = spec._definitions['CustomPetB']['properties']\n+\n+ assert props_0['name']['type'] == 'string'\n+ assert 'format' not in props_0['name']\n+\n+ assert props_a['name']['type'] == 'string'\n+ assert props_a['name']['format'] == 'date-time'\n+\n+ assert props_b['name']['type'] == 'integer'\n+ assert props_b['name']['format'] == 'int32'\n+\nclass TestOperationHelper:\ndef test_schema(self, spec):\n"
}
]
| Python | MIT License | marshmallow-code/apispec | simple decorator test |
394,026 | 03.08.2017 19:14:25 | 25,200 | 4653add23e1b68aa8cc3022be019612f035aa224 | im a author now! | [
{
"change_type": "MODIFY",
"old_path": "AUTHORS.rst",
"new_path": "AUTHORS.rst",
"diff": "@@ -36,3 +36,4 @@ Contributors (chronological)\n- Yoichi NAKAYAMA `@yoichi <https://github.com/yoichi>`_\n- Douglas Anderson `@djanderson <https://github.com/djanderson>`_\n- Marat Sharafutdinov `@decaz <https://github.com/decaz>`_\n+- Daniel Radetsky `@dradetsky <https://github.com/dradetsky>`_\n"
}
]
| Python | MIT License | marshmallow-code/apispec | im a author now! |
394,026 | 03.08.2017 19:21:16 | 25,200 | c816ad5614926e1dc7080495244ae92131044101 | at least some dox | [
{
"change_type": "MODIFY",
"old_path": "docs/using_plugins.rst",
"new_path": "docs/using_plugins.rst",
"diff": "@@ -194,6 +194,24 @@ If your API uses `method-based dispatching <http://flask.pocoo.org/docs/0.12/vie\n# 'post': {}}}\n#\n+Note that by default, apispec only knows how to set the type of\n+built-in marshmallow fields. If you want to generate definitions for\n+schemas with custom fields, use the\n+`apispec.ext.marshmallow.swagger.map_to_swagger_field` decorator:\n+\n+.. code-block:: python\n+\n+ from marshmallow.fields import Integer\n+\n+ @map_to_swagger_field(Integer):\n+ class MyCustomFieldThatsKindaLikeAnInteger(Integer):\n+ ...\n+\n+ @map_to_swagger_field('string', 'uuid')\n+ class MyOtherCustomField(Integer):\n+ ...\n+\n+\nNext Steps\n----------\n"
}
]
| Python | MIT License | marshmallow-code/apispec | at least some dox |
394,026 | 03.08.2017 19:25:47 | 25,200 | f4acd57170d7d172670cf8ff6d824bf268d387eb | wait, thats not how you python | [
{
"change_type": "MODIFY",
"old_path": "docs/using_plugins.rst",
"new_path": "docs/using_plugins.rst",
"diff": "@@ -203,7 +203,7 @@ schemas with custom fields, use the\nfrom marshmallow.fields import Integer\n- @map_to_swagger_field(Integer):\n+ @map_to_swagger_field(Integer)\nclass MyCustomFieldThatsKindaLikeAnInteger(Integer):\n...\n"
}
]
| Python | MIT License | marshmallow-code/apispec | wait, thats not how you python |
394,026 | 07.08.2017 11:42:24 | 25,200 | a4a772ff6e81f509f72e23a0f0e553fe817a5ffa | fix ex type, msg | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/swagger.py",
"new_path": "apispec/ext/marshmallow/swagger.py",
"diff": "@@ -58,7 +58,7 @@ def map_to_swagger_field(*args):\nelif len(args) == 2:\nswagger_type_field = args\nelse:\n- raise ArgumentError('pass core marshmallow field type or (type, fmt) pair')\n+ raise TypeError('Pass core marshmallow field type or (type, fmt) pair')\ndef inner(field_type):\nsetattr(field_type, CUSTOM_FIELD_MAPPING_ATTR, swagger_type_field)\n"
}
]
| Python | MIT License | marshmallow-code/apispec | fix ex type, msg |
394,026 | 07.08.2017 11:51:19 | 25,200 | 8255058182c91ce8387f18891ce797c36c4ca018 | error on bad arg | [
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_marshmallow.py",
"new_path": "tests/test_ext_marshmallow.py",
"diff": "@@ -48,6 +48,11 @@ class TestCustomField:\nclass CustomNameB(Field):\npass\n+ with pytest.raises(TypeError):\n+ @swagger.map_to_swagger_field('integer')\n+ class BadCustomField(Field):\n+ pass\n+\nclass CustomPetASchema(PetSchema):\nname = CustomNameA()\n"
}
]
| Python | MIT License | marshmallow-code/apispec | error on bad arg |
394,026 | 07.08.2017 14:28:25 | 25,200 | c540eda93686e4d9487f9d8cc58f38233cd3c74c | oops, type not reqd in both cases | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/swagger.py",
"new_path": "apispec/ext/marshmallow/swagger.py",
"diff": "@@ -88,7 +88,7 @@ def _observed_name(field, name):\ndef _get_json_type_for_field(field):\n- if hasattr(type(field), CUSTOM_FIELD_MAPPING_ATTR):\n+ if hasattr(field, CUSTOM_FIELD_MAPPING_ATTR):\njson_type, fmt = getattr(field, CUSTOM_FIELD_MAPPING_ATTR)\nelse:\njson_type, fmt = FIELD_MAPPING.get(type(field), ('string', None))\n"
}
]
| Python | MIT License | marshmallow-code/apispec | oops, type not reqd in both cases |
394,026 | 08.08.2017 11:08:16 | 25,200 | 479128a682ce7a81f30e7462a68dbd5cae4a7ae2 | redundant, and is fine either way | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/swagger.py",
"new_path": "apispec/ext/marshmallow/swagger.py",
"diff": "@@ -41,7 +41,7 @@ FIELD_MAPPING = {\nmarshmallow.fields.List: ('array', None),\n}\n-CUSTOM_FIELD_MAPPING_ATTR = '__custom_swagger_field_mapping'\n+CUSTOM_FIELD_MAPPING_ATTR = '__swagger_field_mapping'\ndef map_to_swagger_field(*args):\n"
}
]
| Python | MIT License | marshmallow-code/apispec | redundant, and is fine either way |
394,026 | 09.08.2017 11:58:33 | 25,200 | 624347adc6606bb600ed96290e222c6411f3edc9 | _field -> _type | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/swagger.py",
"new_path": "apispec/ext/marshmallow/swagger.py",
"diff": "@@ -44,7 +44,7 @@ FIELD_MAPPING = {\nCUSTOM_FIELD_MAPPING_ATTR = '__swagger_field_mapping'\n-def map_to_swagger_field(*args):\n+def map_to_swagger_type(*args):\n\"\"\"\ndecorator to set mapping for custom fields.\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/using_plugins.rst",
"new_path": "docs/using_plugins.rst",
"diff": "@@ -197,17 +197,17 @@ If your API uses `method-based dispatching <http://flask.pocoo.org/docs/0.12/vie\nNote that by default, apispec only knows how to set the type of\nbuilt-in marshmallow fields. If you want to generate definitions for\nschemas with custom fields, use the\n-`apispec.ext.marshmallow.swagger.map_to_swagger_field` decorator:\n+`apispec.ext.marshmallow.swagger.map_to_swagger_type` decorator:\n.. code-block:: python\nfrom marshmallow.fields import Integer\n- @map_to_swagger_field(Integer)\n+ @map_to_swagger_type(Integer)\nclass MyCustomFieldThatsKindaLikeAnInteger(Integer):\n...\n- @map_to_swagger_field('string', 'uuid')\n+ @map_to_swagger_type('string', 'uuid')\nclass MyOtherCustomField(Integer):\n...\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_marshmallow.py",
"new_path": "tests/test_ext_marshmallow.py",
"diff": "@@ -40,16 +40,16 @@ class TestCustomField:\ndef test_can_use_custom_field_decorator(self, spec):\n- @swagger.map_to_swagger_field(DateTime)\n+ @swagger.map_to_swagger_type(DateTime)\nclass CustomNameA(Field):\npass\n- @swagger.map_to_swagger_field('integer', 'int32')\n+ @swagger.map_to_swagger_type('integer', 'int32')\nclass CustomNameB(Field):\npass\nwith pytest.raises(TypeError):\n- @swagger.map_to_swagger_field('integer')\n+ @swagger.map_to_swagger_type('integer')\nclass BadCustomField(Field):\npass\n"
}
]
| Python | MIT License | marshmallow-code/apispec | _field -> _type |
393,986 | 15.08.2017 20:46:43 | 21,600 | 1271fa493fad692c29ceab44c40cf53e3f8b07b1 | Don't catch/pass YAMLError when parsing docstring fails.
The current behavior is to swallow any parse errors silently, which makes
trying to add more than a trivial apispec docstring confusing and frustrating.
See issue for more discussion. | [
{
"change_type": "MODIFY",
"old_path": "apispec/utils.py",
"new_path": "apispec/utils.py",
"diff": "@@ -60,10 +60,7 @@ def load_yaml_from_docstring(docstring):\nyaml_string = \"\\n\".join(split_lines[cut_from:])\nyaml_string = dedent(yaml_string)\n- try:\nreturn yaml.load(yaml_string)\n- except yaml.YAMLError:\n- return None\nPATH_KEYS = set([\n'get',\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Don't catch/pass YAMLError when parsing docstring fails.
The current behavior is to swallow any parse errors silently, which makes
trying to add more than a trivial apispec docstring confusing and frustrating.
See issue #135 for more discussion. |
394,001 | 30.08.2017 23:39:59 | -32,400 | ea581ed6a9c02a62231aa1795d35478f2f6353aa | use "with" statement to recover context after add_path | [
{
"change_type": "MODIFY",
"old_path": "README.rst",
"new_path": "README.rst",
"diff": "@@ -68,12 +68,10 @@ Example Application\npet = get_random_pet()\nreturn jsonify(PetSchema().dump(pet).data)\n- ctx = app.test_request_context()\n- ctx.push()\n-\n# Register entities and paths\nspec.definition('Category', schema=CategorySchema)\nspec.definition('Pet', schema=PetSchema)\n+ with app.test_request_context():\nspec.add_path(view=random_pet)\n"
},
{
"change_type": "MODIFY",
"old_path": "apispec/ext/flask.py",
"new_path": "apispec/ext/flask.py",
"diff": "@@ -21,7 +21,7 @@ Passing a view function::\n'''\nreturn 'detail for gist {}'.format(gist_id)\n- app.test_request_context().push()\n+ with app.test_request_context():\nspec.add_path(view=gist_detail)\nprint(spec.to_dict()['paths'])\n# {'/gists/{gist_id}': {'get': {'responses': {200: {'schema': {'$ref': '#/definitions/Gist'}}}},\n@@ -52,9 +52,9 @@ Passing a method view function::\ndef post(self):\npass\n- app.test_request_context().push()\nmethod_view = GistApi.as_view('gists')\napp.add_url_rule(\"/gists\", view_func=method_view)\n+ with app.test_request_context():\nspec.add_path(view=method_view)\nprint(spec.to_dict()['paths'])\n# {'/gists': {'get': {'responses': {200: {'schema': {'$ref': '#/definitions/Gist'}}}},\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/index.rst",
"new_path": "docs/index.rst",
"diff": "@@ -59,12 +59,10 @@ Example Application\npet = get_random_pet()\nreturn jsonify(PetSchema().dump(pet).data)\n- ctx = app.test_request_context()\n- ctx.push()\n-\n# Register entities and paths\nspec.definition('Category', schema=CategorySchema)\nspec.definition('Pet', schema=PetSchema)\n+ with app.test_request_context():\nspec.add_path(view=random_pet)\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/using_plugins.rst",
"new_path": "docs/using_plugins.rst",
"diff": "@@ -135,9 +135,7 @@ The Flask plugin allows us to pass this view to `spec.add_path <apispec.APISpec.\n# Since add_path inspects the view and its route,\n# we need to be in a Flask request context\n- ctx = app.test_request_context()\n- ctx.push()\n-\n+ with app.test_request_context():\nspec.add_path(view=gist_detail)\n@@ -184,9 +182,9 @@ If your API uses `method-based dispatching <http://flask.pocoo.org/docs/0.12/vie\ndef post(self):\npass\n- app.test_request_context().push()\nmethod_view = GistApi.as_view('gist')\napp.add_url_rule(\"/gist\", view_func=method_view)\n+ with app.test_request_context():\nspec.add_path(view=method_view)\nprint(spec.to_dict()['paths'])\n# {'/gist': {'get': {'description': 'get a gist',\n"
}
]
| Python | MIT License | marshmallow-code/apispec | use "with" statement to recover context after add_path |
394,001 | 30.08.2017 23:44:14 | -32,400 | c8a687db5bb3942d2f849b52b1efa12da6d26ee3 | bottle does not have test_request_context | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/bottle.py",
"new_path": "apispec/ext/bottle.py",
"diff": "@@ -17,7 +17,6 @@ to `add_path`.\n'''\nreturn 'detail for gist {}'.format(gist_id)\n- app.test_request_context().push()\nspec.add_path(view=gist_detail)\nprint(spec.to_dict()['paths'])\n# {'/gists/{gist_id}': {'get': {'responses': {200: {'schema': {'$ref': '#/definitions/Gist'}}}}}}\n"
}
]
| Python | MIT License | marshmallow-code/apispec | bottle does not have test_request_context |
394,001 | 03.09.2017 07:35:45 | -32,400 | a4092b6a90041cc68fa4146a3dd378a89d78c09d | Skip non-dict elements on resolve to avoid AttributeError
> for response in operation.get('responses', {}).values():
E AttributeError: 'str' object has no attribute 'get'
apispec/ext/marshmallow/__init__.py:131: AttributeError | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/__init__.py",
"new_path": "apispec/ext/marshmallow/__init__.py",
"diff": "@@ -126,6 +126,8 @@ def schema_path_helper(spec, view=None, **kwargs):\nreturn\noperations = operations.copy()\nfor operation in operations.values():\n+ if not isinstance(operation, dict):\n+ continue\nif 'parameters' in operation:\noperation['parameters'] = resolve_parameters(spec, operation['parameters'])\nfor response in operation.get('responses', {}).values():\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_marshmallow.py",
"new_path": "tests/test_ext_marshmallow.py",
"diff": "@@ -234,6 +234,32 @@ class TestOperationHelper:\n'items': {'$ref': '#/definitions/Pet'}\n}\n+ def test_non_http_method_in_docstring(self, spec):\n+ def pet_view():\n+ \"\"\"Not much to see here.\n+\n+ ---\n+ x-extension: value\n+ get:\n+ responses:\n+ 200:\n+ schema:\n+ type: array\n+ items: tests.schemas.PetSchema\n+ foo:\n+ description: not a valid operation\n+ responses:\n+ 200:\n+ description: more junk\n+ \"\"\"\n+ return '...'\n+\n+ spec.add_path(path='/pet', view=pet_view)\n+ p = spec._paths['/pet']\n+ assert 'get' in p\n+ assert 'x-extension' in p\n+ assert 'foo' not in p\n+\ndef test_schema_global_state_untouched_2json(self):\nassert RunSchema._declared_fields['sample']._Nested__schema is None\ndata = swagger.schema2jsonschema(RunSchema)\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Skip non-dict elements on resolve to avoid AttributeError
> for response in operation.get('responses', {}).values():
E AttributeError: 'str' object has no attribute 'get'
apispec/ext/marshmallow/__init__.py:131: AttributeError |
394,001 | 03.09.2017 08:32:32 | -32,400 | 5d205ebc96a148e05b2c150f81315198727414a6 | Extract operation resolvers and execute them after path helpers
Result of path helper of web framework extension will be resolved
by marshmallow extension regardless of the order of extensions. | [
{
"change_type": "MODIFY",
"old_path": "apispec/core.py",
"new_path": "apispec/core.py",
"diff": "@@ -108,6 +108,7 @@ class APISpec(object):\nself.plugins = {}\nself._definition_helpers = []\nself._path_helpers = []\n+ self._operation_resolvers = []\n# {'get': {200: [my_helper]}}\nself._response_helpers = {}\n@@ -183,6 +184,9 @@ class APISpec(object):\nret.path = normalize_path(ret.path)\npath.update(ret)\noperations = ret.operations\n+ if operations:\n+ for func in self._operation_resolvers:\n+ func(self, path=path, operations=operations, **kwargs)\nif not path.path:\nraise APISpecError('Path template is not specified')\n@@ -290,6 +294,17 @@ class APISpec(object):\n\"\"\"\nself._path_helpers.append(func)\n+ def register_operation_resolver(self, func):\n+ \"\"\"Register a new operation resolver. The helper **must** meet the following conditions:\n+\n+ - Receive the `APISpec` instance as the first argument.\n+ - Receive ``operations`` as a keyword argument.\n+ - Include ``**kwargs`` in signature.\n+\n+ The helper may define any named arguments in its signature.\n+ \"\"\"\n+ self._operation_resolvers.append(func)\n+\ndef register_response_helper(self, func, method, status_code):\n\"\"\"Register a new response helper. The helper **must** meet the following conditions:\n"
},
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/__init__.py",
"new_path": "apispec/ext/marshmallow/__init__.py",
"diff": "@@ -125,13 +125,16 @@ def schema_path_helper(spec, view=None, **kwargs):\nif not operations:\nreturn\noperations = operations.copy()\n+ return Path(operations=operations)\n+\n+\n+def schema_operation_resolver(spec, operations, **kwargs):\nfor operation in operations.values():\nif 'parameters' in operation:\noperation['parameters'] = resolve_parameters(spec, operation['parameters'])\nfor response in operation.get('responses', {}).values():\nif 'schema' in response:\nresponse['schema'] = resolve_schema_dict(spec, response['schema'])\n- return Path(operations=operations)\ndef resolve_parameters(spec, parameters):\n@@ -182,3 +185,4 @@ def setup(spec):\n\"\"\"Setup for the marshmallow plugin.\"\"\"\nspec.register_definition_helper(schema_definition_helper)\nspec.register_path_helper(schema_path_helper)\n+ spec.register_operation_resolver(schema_operation_resolver)\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/writing_plugins.rst",
"new_path": "docs/writing_plugins.rst",
"diff": "@@ -12,6 +12,7 @@ There are three types of helper functions:\n* Definition helpers\n* Path helpers\n+* Operation resolvers\n* Response helpers\nEach helper function type modifies a different `apispec.APISpec` method. For example, path helpers modify `apispec.APISpec.add_path`.\n@@ -97,6 +98,6 @@ To use the plugin:\nNext Steps\n----------\n-* To learn more about how to write helper functions, consult the :ref:`Core API docs <core_api>` for `register_definition_helper <apispec.APISpec.register_definition_helper>`, `register_path_helper <apispec.APISpec.register_path_helper>`, and `register_response_helper <apispec.APISpec.register_response_helper>`\n+* To learn more about how to write helper functions, consult the :ref:`Core API docs <core_api>` for `register_definition_helper <apispec.APISpec.register_definition_helper>`, `register_path_helper <apispec.APISpec.register_path_helper>`, `register_operation_resolver <apispec.APISpec.register_operation_resolver>`, and `register_response_helper <apispec.APISpec.register_response_helper>`\n* View the source for apispec's bundled plugins, e.g. `apispec.ext.flask </_modules/apispec/ext/flask.html>`_\n* Check out some projects using apispec: https://github.com/marshmallow-code/apispec/wiki/Ecosystem\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tests/test_ext_order.py",
"diff": "+# -*- coding: utf-8 -*-\n+from apispec import APISpec\n+from bottle import route\n+from flask import Flask\n+from flask.views import MethodView\n+from tornado.web import RequestHandler\n+\n+def create_spec(ext_list):\n+ return APISpec(\n+ title='Swagger Petstore',\n+ version='1.0.0',\n+ description='This is a sample Petstore server. You can find out more '\n+ 'about Swagger at <a href=\\\"http://swagger.wordnik.com\\\">http://swagger.wordnik.com</a> '\n+ 'or on irc.freenode.net, #swagger. For this sample, you can use the api '\n+ 'key \\\"special-key\\\" to test the authorization filters',\n+ plugins=['apispec.ext.' + name for name in ext_list]\n+ )\n+\n+def confirm_ext_order_independency(web_framework, **kwargs_for_add_path):\n+ extensions = [web_framework, 'marshmallow']\n+ specs = []\n+ for reverse in (False, True):\n+ print(reverse)\n+ if reverse:\n+ spec = create_spec(reversed(extensions))\n+ else:\n+ spec = create_spec(extensions)\n+ spec.add_path(**kwargs_for_add_path)\n+ get_op = spec._paths['/hello']['get']\n+ assert get_op['description'] == 'get a greeting'\n+ assert isinstance(get_op['responses'][200]['schema'], dict)\n+ specs.append(spec)\n+ assert specs[0].to_dict() == specs[1].to_dict()\n+\n+class TestExtOrder:\n+ def test_bottle(self):\n+ @route('/hello')\n+ def hello():\n+ \"\"\"A greeting endpoint.\n+\n+ ---\n+ get:\n+ description: get a greeting\n+ responses:\n+ 200:\n+ description: a pet to be returned\n+ schema: tests.schemas.PetSchema\n+ \"\"\"\n+ return 'hi'\n+\n+ confirm_ext_order_independency('bottle', view=hello)\n+\n+ def test_flask(self):\n+ app = Flask(__name__)\n+\n+ @app.route('/hello')\n+ def hello():\n+ \"\"\"A greeting endpoint.\n+\n+ ---\n+ get:\n+ description: get a greeting\n+ responses:\n+ 200:\n+ description: a pet to be returned\n+ schema: tests.schemas.PetSchema\n+ \"\"\"\n+ return 'hi'\n+\n+ with app.test_request_context():\n+ confirm_ext_order_independency('flask', view=hello)\n+\n+ def test_flask_method_view(self):\n+ app = Flask(__name__)\n+\n+ class HelloApi(MethodView):\n+ def get(self_):\n+ \"\"\"A greeting endpoint.\n+\n+ ---\n+ description: get a greeting\n+ responses:\n+ 200:\n+ description: a pet to be returned\n+ schema: tests.schemas.PetSchema\n+ \"\"\"\n+ return 'hi'\n+\n+ method_view = HelloApi.as_view('hi')\n+ app.add_url_rule(\"/hello\", view_func=method_view)\n+ with app.test_request_context():\n+ confirm_ext_order_independency('flask', view=method_view)\n+\n+ def test_tornado(self):\n+ class TornadoHelloHandler(RequestHandler):\n+ def get(self_):\n+ \"\"\"A greeting endpoint.\n+\n+ ---\n+ description: get a greeting\n+ responses:\n+ 200:\n+ description: a pet to be returned\n+ schema: tests.schemas.PetSchema\n+ \"\"\"\n+ self_.write('hi')\n+\n+ urlspec = (r'/hello', TornadoHelloHandler)\n+ confirm_ext_order_independency('tornado', urlspec=urlspec)\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Extract operation resolvers and execute them after path helpers
Result of path helper of web framework extension will be resolved
by marshmallow extension regardless of the order of extensions. |
394,001 | 03.09.2017 10:37:23 | -32,400 | a16ff2fd7d5805e1fff9b128f4973c823bedbb13 | remove duplicate test covered by test_ext_order.py | [
{
"change_type": "DELETE",
"old_path": "tests/test_ext_tornado_marshmallow.py",
"new_path": null,
"diff": "-# -*- coding: utf-8 -*-\n-import pytest\n-\n-from apispec import APISpec\n-from apispec.ext.marshmallow import swagger\n-from tornado.web import RequestHandler\n-from .schemas import PetSchema\n-\[email protected]()\n-def spec():\n- return APISpec(\n- title='Swagger Petstore',\n- version='1.0.0',\n- description='This is a sample Petstore server. You can find out more '\n- 'about Swagger at <a href=\\\"http://swagger.wordnik.com\\\">'\n- 'http://swagger.wordnik.com</a> or on irc.freenode.net, #swagger.'\n- 'For this sample, you can use the api key \\\"special-key\\\" to test the'\n- 'authorization filters',\n- plugins=[\n- 'apispec.ext.tornado',\n- 'apispec.ext.marshmallow'\n- ]\n- )\n-\n-\n-class TestPathHelpers:\n-\n- def test_integration_with_docstring_introspection(self, spec):\n-\n- class HelloHandler(RequestHandler):\n- def get(self):\n- \"\"\"Get a greeting endpoint.\n- ---\n- description: get a greeting\n- responses:\n- 200:\n- description: a pet to be returned\n- schema: tests.schemas.PetSchema\n- \"\"\"\n- self.write(\"hello\")\n-\n- urlspec = (r'/hello', HelloHandler)\n- spec.add_path(urlspec=urlspec)\n- get_op = spec._paths['/hello']['get']\n- assert get_op['description'] == 'get a greeting'\n- response = get_op['responses'][200]\n- assert response['description'] == 'a pet to be returned'\n- assert response['schema'] == swagger.schema2jsonschema(PetSchema)\n"
}
]
| Python | MIT License | marshmallow-code/apispec | remove duplicate test covered by test_ext_order.py |
394,001 | 03.09.2017 20:56:15 | -32,400 | 695396d69ba42dfb7cdc57d172e2874b73af3abf | modify method name to clarify the purpose | [
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_marshmallow.py",
"new_path": "tests/test_ext_marshmallow.py",
"diff": "@@ -234,7 +234,7 @@ class TestOperationHelper:\n'items': {'$ref': '#/definitions/Pet'}\n}\n- def test_non_http_method_in_docstring(self, spec):\n+ def test_other_than_http_method_in_docstring(self, spec):\ndef pet_view():\n\"\"\"Not much to see here.\n"
}
]
| Python | MIT License | marshmallow-code/apispec | modify method name to clarify the purpose |
394,001 | 10.09.2017 17:37:31 | -32,400 | 623fef3da0353a359d6a27c4e41f1cb786384ff5 | Handle multiple fields with location='json' correctly.
Fixes
* Merge results from field2parameter.
* Modify input data for test_field_required since required
fields in body are treated differently. | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/swagger.py",
"new_path": "apispec/ext/marshmallow/swagger.py",
"diff": "@@ -390,21 +390,28 @@ def fields2parameters(fields, schema=None, spec=None, use_refs=True,\nexclude_fields = getattr(getattr(schema, 'Meta', None), 'exclude', [])\ndump_only_fields = getattr(getattr(schema, 'Meta', None), 'dump_only', [])\n- return [\n- field2parameter(\n- field_obj,\n+ parameters = []\n+ body_param = None\n+ for field_name, field_obj in iteritems(fields):\n+ if (field_name in exclude_fields\n+ or field_obj.dump_only\n+ or field_name in dump_only_fields):\n+ continue\n+ param = field2parameter(field_obj,\nname=_observed_name(field_obj, field_name),\nspec=spec,\nuse_refs=use_refs,\n- default_in=default_in\n- )\n- for field_name, field_obj in iteritems(fields)\n- if not (\n- field_name in exclude_fields or\n- field_obj.dump_only or\n- field_name in dump_only_fields\n- )\n- ]\n+ default_in=default_in)\n+ if param['in'] == 'body' and body_param is not None:\n+ body_param['schema']['properties'].update(param['schema']['properties'])\n+ required_fields = param['schema'].get('required', [])\n+ if required_fields:\n+ body_param['schema']['required'] += required_fields\n+ else:\n+ if param['in'] == 'body':\n+ body_param = param\n+ parameters.append(param)\n+ return parameters\ndef field2parameter(field, name='body', spec=None, use_refs=True, default_in='body'):\n@@ -444,18 +451,20 @@ def property2parameter(prop, name='body', required=False, multiple=False, locati\nswagger_location = __location_map__.get(location, swagger_default_in)\nret = {\n'in': swagger_location,\n- 'required': required,\n'name': name,\n}\nif swagger_location == 'body':\n+ ret['required'] = False\nret['name'] = 'body'\n- ret['schema'] = {}\n- schema_props = {}\n- if name:\n- schema_props[name] = prop\n- ret['schema']['properties'] = schema_props\n+ ret['schema'] = {\n+ 'type': 'object',\n+ 'properties': {name: prop} if name else {},\n+ }\n+ if name and required:\n+ ret['schema']['required'] = [name]\nelse:\n+ ret['required'] = required\nif multiple:\nret['collectionFormat'] = 'multi'\nret.update(prop)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_swagger.py",
"new_path": "tests/test_swagger.py",
"diff": "@@ -95,6 +95,21 @@ class TestMarshmallowFieldToSwagger:\nres = swagger.fields2parameters(field_dict, default_in='headers')\nassert res[0]['in'] == 'query'\n+ def test_fields_with_multiple_json_locations(self):\n+ field_dict = {'field1': fields.Str(location='json', required=True),\n+ 'field2': fields.Str(location='json', required=True),\n+ 'field3': fields.Str(location='json')}\n+ res = swagger.fields2parameters(field_dict, default_in=None)\n+ assert len(res) == 1\n+ assert res[0]['in'] == 'body'\n+ assert res[0]['required'] is False\n+ assert 'field1' in res[0]['schema']['properties']\n+ assert 'field2' in res[0]['schema']['properties']\n+ assert 'field3' in res[0]['schema']['properties']\n+ assert 'required' in res[0]['schema']\n+ assert res[0]['schema']['required'] == ['field1', 'field2']\n+ assert res == swagger.fields2parameters(field_dict, default_in='body')\n+\ndef test_fields2parameters_does_not_modify_metadata(self):\nfield_dict = {'field': fields.Str(location='querystring')}\nres = swagger.fields2parameters(field_dict, default_in='headers')\n@@ -344,7 +359,7 @@ class TestMarshmallowSchemaToParameters:\nassert res['collectionFormat'] == 'multi'\ndef test_field_required(self):\n- field = fields.Str(required=True)\n+ field = fields.Str(required=True, location='query')\nres = swagger.field2parameter(field, name='field')\nassert res['required'] is True\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Handle multiple fields with location='json' correctly.
Fixes https://github.com/marshmallow-code/apispec/issues/75
* Merge results from field2parameter.
* Modify input data for test_field_required since required
fields in body are treated differently. |
394,001 | 11.09.2017 06:31:53 | -32,400 | 6a80b6652df17fd1e8bf3af1937146326af51cc2 | Don't assume the dict iteration order in the test | [
{
"change_type": "MODIFY",
"old_path": "tests/test_swagger.py",
"new_path": "tests/test_swagger.py",
"diff": "@@ -107,7 +107,9 @@ class TestMarshmallowFieldToSwagger:\nassert 'field2' in res[0]['schema']['properties']\nassert 'field3' in res[0]['schema']['properties']\nassert 'required' in res[0]['schema']\n- assert res[0]['schema']['required'] == ['field1', 'field2']\n+ assert len(res[0]['schema']['required']) == 2\n+ assert 'field1' in res[0]['schema']['required']\n+ assert 'field2' in res[0]['schema']['required']\nassert res == swagger.fields2parameters(field_dict, default_in='body')\ndef test_fields2parameters_does_not_modify_metadata(self):\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Don't assume the dict iteration order in the test |
394,001 | 11.09.2017 06:43:39 | -32,400 | 8374cf072273c9f5f80ab4ea60a10c36fb324e46 | Remove comparison with default_in='body'
In general they differ at res[0]['schema']['required'] | [
{
"change_type": "MODIFY",
"old_path": "tests/test_swagger.py",
"new_path": "tests/test_swagger.py",
"diff": "@@ -110,7 +110,6 @@ class TestMarshmallowFieldToSwagger:\nassert len(res[0]['schema']['required']) == 2\nassert 'field1' in res[0]['schema']['required']\nassert 'field2' in res[0]['schema']['required']\n- assert res == swagger.fields2parameters(field_dict, default_in='body')\ndef test_fields2parameters_does_not_modify_metadata(self):\nfield_dict = {'field': fields.Str(location='querystring')}\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Remove comparison with default_in='body'
In general they differ at res[0]['schema']['required'] |
394,033 | 03.10.2017 14:21:58 | -10,800 | 4ed91d68c3e0c146f84d804a2e5acf88cc8a8faa | Fix swagger location mapping for default_in param in fields2parameters | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/swagger.py",
"new_path": "apispec/ext/marshmallow/swagger.py",
"diff": "@@ -369,7 +369,8 @@ def fields2parameters(fields, schema=None, spec=None, use_refs=True,\nhttps://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameterObject\n\"\"\"\n- if default_in == 'body':\n+ swagger_default_in = __location_map__.get(default_in, default_in)\n+ if swagger_default_in == 'body':\nif schema is not None:\n# Prevent circular import\nfrom apispec.ext.marshmallow import resolve_schema_dict\n@@ -378,7 +379,7 @@ def fields2parameters(fields, schema=None, spec=None, use_refs=True,\nprop = fields2jsonschema(fields, spec=spec, use_refs=use_refs, dump=False)\nreturn [{\n- 'in': default_in,\n+ 'in': swagger_default_in,\n'required': required,\n'name': name,\n'schema': prop,\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_swagger.py",
"new_path": "tests/test_swagger.py",
"diff": "@@ -129,6 +129,15 @@ class TestMarshmallowFieldToSwagger:\nres = swagger.fields2parameters(field_dict, default_in='headers')\nassert res[0]['in'] == 'header'\n+ def test_fields_default_location_mapping_if_schema_many(self):\n+\n+ class ExampleSchema(Schema):\n+ id = fields.Int()\n+\n+ schema = ExampleSchema(many=True)\n+ res = swagger.fields2parameters(schema.fields, schema=schema, default_in='json')\n+ assert res[0]['in'] == 'body'\n+\ndef test_fields_with_dump_only(self):\nclass UserSchema(Schema):\nname = fields.Str(dump_only=True)\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Fix swagger location mapping for default_in param in fields2parameters |
394,000 | 02.10.2017 22:31:06 | 14,400 | cb763be3c3763eff8dc6a247ad93ffef47a31c5c | maps validate.Equal to property with enum 1 choice | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/swagger.py",
"new_path": "apispec/ext/marshmallow/swagger.py",
"diff": "@@ -112,15 +112,20 @@ def field2choices(field):\n:param Field field: A marshmallow field.\n:rtype: set\n\"\"\"\n- validators = [\n+ comparable = {\n+ validator.comparable for validator in field.validators\n+ if hasattr(validator, 'comparable')\n+ }\n+ if comparable:\n+ return comparable\n+\n+ choices = [\nOrderedSet(validator.choices) for validator in field.validators\nif hasattr(validator, 'choices')\n]\n- return (\n- functools.reduce(operator.and_, validators)\n- if validators\n- else None\n- )\n+ if choices:\n+ return functools.reduce(operator.and_, choices)\n+\ndef field2range(field):\n\"\"\"Return the dictionary of swagger field attributes for a set of\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_swagger.py",
"new_path": "tests/test_swagger.py",
"diff": "@@ -154,6 +154,11 @@ class TestMarshmallowFieldToSwagger:\nres = swagger.field2property(field)\nassert set(res['enum']) == {'freddie', 'brian', 'john'}\n+ def test_field_with_equal(self):\n+ field = fields.Str(validate=validate.Equal('only choice'))\n+ res = swagger.field2property(field)\n+ assert res['enum'] == ['only choice']\n+\ndef test_only_allows_valid_properties_in_metadata(self):\nfield = fields.Str(\ndefault='foo',\n"
}
]
| Python | MIT License | marshmallow-code/apispec | maps validate.Equal to property with enum 1 choice |
394,001 | 29.10.2017 10:52:07 | -32,400 | c4181d49bc633dd175383928cfdefef0c6dd3fce | Update total number of helper function types. | [
{
"change_type": "MODIFY",
"old_path": "docs/writing_plugins.rst",
"new_path": "docs/writing_plugins.rst",
"diff": "@@ -8,7 +8,7 @@ Helper Functions\nPlugins are comprised of \"helper\" functions that augment the behavior of `apispec.APISpec` methods.\n-There are three types of helper functions:\n+There are four types of helper functions:\n* Definition helpers\n* Path helpers\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Update total number of helper function types. |
394,001 | 30.10.2017 21:23:22 | -32,400 | d2cae56d32d5e011104a97425b13cd65544d9aca | rename hook to be consistent with existing ones | [
{
"change_type": "MODIFY",
"old_path": "apispec/core.py",
"new_path": "apispec/core.py",
"diff": "@@ -108,7 +108,7 @@ class APISpec(object):\nself.plugins = {}\nself._definition_helpers = []\nself._path_helpers = []\n- self._operation_resolvers = []\n+ self._operation_helpers = []\n# {'get': {200: [my_helper]}}\nself._response_helpers = {}\n@@ -185,7 +185,7 @@ class APISpec(object):\npath.update(ret)\noperations = ret.operations\nif operations:\n- for func in self._operation_resolvers:\n+ for func in self._operation_helpers:\nfunc(self, path=path, operations=operations, **kwargs)\nif not path.path:\n@@ -294,8 +294,8 @@ class APISpec(object):\n\"\"\"\nself._path_helpers.append(func)\n- def register_operation_resolver(self, func):\n- \"\"\"Register a new operation resolver. The helper **must** meet the following conditions:\n+ def register_operation_helper(self, func):\n+ \"\"\"Register a new operation helper. The helper **must** meet the following conditions:\n- Receive the `APISpec` instance as the first argument.\n- Receive ``operations`` as a keyword argument.\n@@ -303,7 +303,7 @@ class APISpec(object):\nThe helper may define any named arguments in its signature.\n\"\"\"\n- self._operation_resolvers.append(func)\n+ self._operation_helpers.append(func)\ndef register_response_helper(self, func, method, status_code):\n\"\"\"Register a new response helper. The helper **must** meet the following conditions:\n"
},
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/__init__.py",
"new_path": "apispec/ext/marshmallow/__init__.py",
"diff": "@@ -185,4 +185,4 @@ def setup(spec):\n\"\"\"Setup for the marshmallow plugin.\"\"\"\nspec.register_definition_helper(schema_definition_helper)\nspec.register_path_helper(schema_path_helper)\n- spec.register_operation_resolver(schema_operation_resolver)\n+ spec.register_operation_helper(schema_operation_resolver)\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/writing_plugins.rst",
"new_path": "docs/writing_plugins.rst",
"diff": "@@ -12,7 +12,7 @@ There are four types of helper functions:\n* Definition helpers\n* Path helpers\n-* Operation resolvers\n+* Operation helpers\n* Response helpers\nEach helper function type modifies a different `apispec.APISpec` method. For example, path helpers modify `apispec.APISpec.add_path`.\n@@ -98,6 +98,6 @@ To use the plugin:\nNext Steps\n----------\n-* To learn more about how to write helper functions, consult the :ref:`Core API docs <core_api>` for `register_definition_helper <apispec.APISpec.register_definition_helper>`, `register_path_helper <apispec.APISpec.register_path_helper>`, `register_operation_resolver <apispec.APISpec.register_operation_resolver>`, and `register_response_helper <apispec.APISpec.register_response_helper>`\n+* To learn more about how to write helper functions, consult the :ref:`Core API docs <core_api>` for `register_definition_helper <apispec.APISpec.register_definition_helper>`, `register_path_helper <apispec.APISpec.register_path_helper>`, `register_operation_helper <apispec.APISpec.register_operation_helper>`, and `register_response_helper <apispec.APISpec.register_response_helper>`\n* View the source for apispec's bundled plugins, e.g. `apispec.ext.flask </_modules/apispec/ext/flask.html>`_\n* Check out some projects using apispec: https://github.com/marshmallow-code/apispec/wiki/Ecosystem\n"
}
]
| Python | MIT License | marshmallow-code/apispec | rename hook to be consistent with existing ones |
394,000 | 05.12.2017 13:29:10 | 18,000 | d46a170823f045d4efcc6c07474e6f607f26aa74 | fixes a WindowsError
The arguments for subprocess.check_output are hard coded so running
in shell is safe. | [
{
"change_type": "MODIFY",
"old_path": "apispec/utils.py",
"new_path": "apispec/utils.py",
"diff": "@@ -96,6 +96,7 @@ def validate_swagger(spec):\nsubprocess.check_output(\n['swagger-tools', 'validate', fp.name],\nstderr=subprocess.STDOUT,\n+ shell=True,\n)\nexcept subprocess.CalledProcessError as error:\nraise exceptions.SwaggerError(error.output.decode('utf-8'))\n"
}
]
| Python | MIT License | marshmallow-code/apispec | fixes a WindowsError
The arguments for subprocess.check_output are hard coded so running
in shell is safe. |
393,992 | 08.11.2017 16:53:21 | -3,600 | d5f9e929cb58032cb895efb6a0ea8f8abfa235ce | Permit auto generation of definition schema names | [
{
"change_type": "MODIFY",
"old_path": "apispec/core.py",
"new_path": "apispec/core.py",
"diff": "@@ -91,15 +91,25 @@ class APISpec(object):\nSee https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#infoObject\n:param \\*\\*dict options: Optional top-level keys\nSee https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#swagger-object\n+ :param callable schema_name_resolver_callable: callable who generate the schema definition name\n\"\"\"\n- def __init__(self, title, version, plugins=(), info=None, **options):\n+ def __init__(\n+ self,\n+ title,\n+ version,\n+ plugins=(),\n+ info=None,\n+ schema_name_resolver_callable=None,\n+ **options\n+ ):\nself.info = {\n'title': title,\n'version': version,\n}\nself.info.update(info or {})\nself.options = options\n+ self.schema_name_resolver_callable = schema_name_resolver_callable\n# Metadata\nself._definitions = {}\nself._parameters = {}\n"
},
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/__init__.py",
"new_path": "apispec/ext/marshmallow/__init__.py",
"diff": "@@ -162,6 +162,17 @@ def resolve_schema_dict(spec, schema, dump=True, use_instances=False):\nschema_cls = schema\nelse:\nschema_cls = resolve_schema_cls(schema)\n+\n+ # Auto reference schema if available\n+ if schema_cls not in plug.get('refs', {}):\n+ if spec.schema_name_resolver_callable:\n+ definition_name = spec.schema_name_resolver_callable(\n+ schema_cls)\n+ spec.definition(\n+ definition_name,\n+ schema=schema\n+ )\n+\nif schema_cls in plug.get('refs', {}):\nref_schema = {'$ref': '#/definitions/{0}'.format(plug['refs'][schema_cls])}\nif getattr(schema, 'many', False):\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Permit auto generation of definition schema names |
393,992 | 09.11.2017 08:56:15 | -3,600 | 0444fa992352398445070d31aae0785fdd218e66 | Temporary version for setup.py requirements | [
{
"change_type": "MODIFY",
"old_path": "setup.py",
"new_path": "setup.py",
"diff": "@@ -34,7 +34,7 @@ def read(fname):\nsetup(\nname='apispec',\n- version=__version__,\n+ version='0.25.4-algoo',\ndescription='A pluggable API specification generator. Currently supports the '\n'OpenAPI specification (f.k.a. Swagger 2.0).',\nlong_description=read('README.rst'),\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Temporary version for setup.py requirements |
393,992 | 09.11.2017 16:25:48 | -3,600 | f4e7c6f6f9cf91c3b6fd421c4ec960049e9e7ee8 | apispec.ext.marshmallow.resolve_schema_dict: use spec only if given | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/__init__.py",
"new_path": "apispec/ext/marshmallow/__init__.py",
"diff": "@@ -165,7 +165,7 @@ def resolve_schema_dict(spec, schema, dump=True, use_instances=False):\n# Auto reference schema if available\nif schema_cls not in plug.get('refs', {}):\n- if spec.schema_name_resolver_callable:\n+ if spec and spec.schema_name_resolver_callable:\ndefinition_name = spec.schema_name_resolver_callable(\nschema_cls)\nspec.definition(\n"
}
]
| Python | MIT License | marshmallow-code/apispec | apispec.ext.marshmallow.resolve_schema_dict: use spec only if given |
393,992 | 09.11.2017 16:31:00 | -3,600 | 5170fc266867013080fdb4053aebefda69848bd4 | More info in doctring of apispec.core.APISpec about schema_name_resolver_callable parameter | [
{
"change_type": "MODIFY",
"old_path": "apispec/core.py",
"new_path": "apispec/core.py",
"diff": "@@ -91,7 +91,12 @@ class APISpec(object):\nSee https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#infoObject\n:param \\*\\*dict options: Optional top-level keys\nSee https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#swagger-object\n- :param callable schema_name_resolver_callable: callable who generate the schema definition name\n+ :param callable schema_name_resolver_callable: callable who generate the\n+ schema definition name. The schema will be given to this callable and\n+ definition name must be returned by callable, ex:\n+\n+ def schema_name_resolver_callable(schema):\n+ return schema.__name__\n\"\"\"\ndef __init__(\n"
}
]
| Python | MIT License | marshmallow-code/apispec | More info in doctring of apispec.core.APISpec about schema_name_resolver_callable parameter |
393,992 | 09.11.2017 16:34:51 | -3,600 | a5431394b607def9847c42b2cb80f3ee64682263 | clean code of apispec.ext.marshmallow.resolve_schema_dict | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/__init__.py",
"new_path": "apispec/ext/marshmallow/__init__.py",
"diff": "@@ -166,12 +166,8 @@ def resolve_schema_dict(spec, schema, dump=True, use_instances=False):\n# Auto reference schema if available\nif schema_cls not in plug.get('refs', {}):\nif spec and spec.schema_name_resolver_callable:\n- definition_name = spec.schema_name_resolver_callable(\n- schema_cls)\n- spec.definition(\n- definition_name,\n- schema=schema\n- )\n+ definition_name = spec.schema_name_resolver_callable(schema_cls)\n+ spec.definition(definition_name, schema=schema)\nif schema_cls in plug.get('refs', {}):\nref_schema = {'$ref': '#/definitions/{0}'.format(plug['refs'][schema_cls])}\n"
}
]
| Python | MIT License | marshmallow-code/apispec | clean code of apispec.ext.marshmallow.resolve_schema_dict |
393,992 | 13.11.2017 10:00:54 | -3,600 | 9451276a0b3b56370707af07145f1f4753be0f2a | add test about auto reference for marshmallow schemas | [
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_marshmallow.py",
"new_path": "tests/test_ext_marshmallow.py",
"diff": "@@ -35,6 +35,45 @@ class TestDefinitionHelper:\nassert props['id']['type'] == 'integer'\nassert props['name']['type'] == 'string'\n+ @pytest.mark.parametrize('schema', [AnalysisSchema, AnalysisSchema()])\n+ def test_resolve_schema_dict_auto_reference(self, schema):\n+ resolver = lambda s: s.__name__\n+ spec = APISpec(\n+ title='Test auto-reference',\n+ version='2.0',\n+ description='Test auto-reference',\n+ plugins=(\n+ 'apispec.ext.marshmallow',\n+ ),\n+ schema_name_resolver_callable=resolver,\n+ )\n+ assert {} == spec._definitions\n+\n+ spec.definition('analysis', schema=schema)\n+ spec.add_path('/test', operations={\n+ 'get': {\n+ 'responses': {\n+ '200': {\n+ 'schema': {\n+ '$ref': '#/definitions/analysis'\n+ }\n+ }\n+ }\n+ }\n+ })\n+\n+ # Other shemas not yet referenced\n+ assert 1 == len(spec._definitions)\n+\n+ spec_dict = spec.to_dict()\n+ assert spec_dict.get('definitions')\n+ assert 'analysis' in spec_dict['definitions']\n+ # Inspect/Read objects will trigger auto reference\n+ json.dumps(spec_dict)\n+ # Other shema is now referenced\n+ assert 2 == len(spec._definitions)\n+ assert 'SampleSchema' in spec_dict['definitions']\n+\nclass TestCustomField:\n"
}
]
| Python | MIT License | marshmallow-code/apispec | add test about auto reference for marshmallow schemas |
393,992 | 13.11.2017 10:02:01 | -3,600 | ef47cbdb72c61cffaffd728ff44780badd1e5d2e | rename schema_name_resolver_callable in schema_name_resolver | [
{
"change_type": "MODIFY",
"old_path": "apispec/core.py",
"new_path": "apispec/core.py",
"diff": "@@ -91,11 +91,11 @@ class APISpec(object):\nSee https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#infoObject\n:param \\*\\*dict options: Optional top-level keys\nSee https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#swagger-object\n- :param callable schema_name_resolver_callable: callable who generate the\n+ :param callable schema_name_resolver: callable who generate the\nschema definition name. The schema will be given to this callable and\ndefinition name must be returned by callable, ex:\n- def schema_name_resolver_callable(schema):\n+ def schema_name_resolver(schema):\nreturn schema.__name__\n\"\"\"\n@@ -105,7 +105,7 @@ class APISpec(object):\nversion,\nplugins=(),\ninfo=None,\n- schema_name_resolver_callable=None,\n+ schema_name_resolver=None,\n**options\n):\nself.info = {\n@@ -114,7 +114,7 @@ class APISpec(object):\n}\nself.info.update(info or {})\nself.options = options\n- self.schema_name_resolver_callable = schema_name_resolver_callable\n+ self.schema_name_resolver = schema_name_resolver\n# Metadata\nself._definitions = {}\nself._parameters = {}\n"
},
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/__init__.py",
"new_path": "apispec/ext/marshmallow/__init__.py",
"diff": "@@ -165,8 +165,8 @@ def resolve_schema_dict(spec, schema, dump=True, use_instances=False):\n# Auto reference schema if available\nif schema_cls not in plug.get('refs', {}):\n- if spec and spec.schema_name_resolver_callable:\n- definition_name = spec.schema_name_resolver_callable(schema_cls)\n+ if spec and spec.schema_name_resolver:\n+ definition_name = spec.schema_name_resolver(schema_cls)\nspec.definition(definition_name, schema=schema)\nif schema_cls in plug.get('refs', {}):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_marshmallow.py",
"new_path": "tests/test_ext_marshmallow.py",
"diff": "@@ -45,7 +45,7 @@ class TestDefinitionHelper:\nplugins=(\n'apispec.ext.marshmallow',\n),\n- schema_name_resolver_callable=resolver,\n+ schema_name_resolver=resolver,\n)\nassert {} == spec._definitions\n"
}
]
| Python | MIT License | marshmallow-code/apispec | rename schema_name_resolver_callable in schema_name_resolver |
393,992 | 13.11.2017 10:04:00 | -3,600 | b189f96016f8a00b660f9628101138f2cd4850de | add test for no auto reference of schema marshmallow when resolver return None | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/__init__.py",
"new_path": "apispec/ext/marshmallow/__init__.py",
"diff": "@@ -167,6 +167,7 @@ def resolve_schema_dict(spec, schema, dump=True, use_instances=False):\nif schema_cls not in plug.get('refs', {}):\nif spec and spec.schema_name_resolver:\ndefinition_name = spec.schema_name_resolver(schema_cls)\n+ if definition_name:\nspec.definition(definition_name, schema=schema)\nif schema_cls in plug.get('refs', {}):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_marshmallow.py",
"new_path": "tests/test_ext_marshmallow.py",
"diff": "@@ -74,6 +74,45 @@ class TestDefinitionHelper:\nassert 2 == len(spec._definitions)\nassert 'SampleSchema' in spec_dict['definitions']\n+ @pytest.mark.parametrize('schema', [AnalysisSchema, AnalysisSchema()])\n+ def test_resolve_schema_dict_auto_reference_return_none(self, schema):\n+ resolver = lambda s: None # this resolver return None\n+ spec = APISpec(\n+ title='Test auto-reference',\n+ version='2.0',\n+ description='Test auto-reference',\n+ plugins=(\n+ 'apispec.ext.marshmallow',\n+ ),\n+ schema_name_resolver=resolver,\n+ )\n+ assert {} == spec._definitions\n+\n+ spec.definition('analysis', schema=schema)\n+ spec.add_path('/test', operations={\n+ 'get': {\n+ 'responses': {\n+ '200': {\n+ 'schema': {\n+ '$ref': '#/definitions/analysis'\n+ }\n+ }\n+ }\n+ }\n+ })\n+\n+ # Other shemas not yet referenced\n+ assert 1 == len(spec._definitions)\n+\n+ spec_dict = spec.to_dict()\n+ assert spec_dict.get('definitions')\n+ assert 'analysis' in spec_dict['definitions']\n+ # Inspect/Read objects will not auto reference because resolver func\n+ # return None\n+ json.dumps(spec_dict)\n+ # Other shema still not referenced\n+ assert 1 == len(spec._definitions)\n+\nclass TestCustomField:\n"
}
]
| Python | MIT License | marshmallow-code/apispec | add test for no auto reference of schema marshmallow when resolver return None |
393,992 | 13.11.2017 10:06:54 | -3,600 | b0cfdf673abaa7be9127c568882d416ccde558be | flake8 compat | [
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_marshmallow.py",
"new_path": "tests/test_ext_marshmallow.py",
"diff": "@@ -37,7 +37,8 @@ class TestDefinitionHelper:\[email protected]('schema', [AnalysisSchema, AnalysisSchema()])\ndef test_resolve_schema_dict_auto_reference(self, schema):\n- resolver = lambda s: s.__name__\n+ def resolver(schema):\n+ return schema.__name__\nspec = APISpec(\ntitle='Test auto-reference',\nversion='2.0',\n@@ -76,7 +77,10 @@ class TestDefinitionHelper:\[email protected]('schema', [AnalysisSchema, AnalysisSchema()])\ndef test_resolve_schema_dict_auto_reference_return_none(self, schema):\n- resolver = lambda s: None # this resolver return None\n+ # this resolver return None\n+ def resolver(schema):\n+ return None\n+\nspec = APISpec(\ntitle='Test auto-reference',\nversion='2.0',\n"
}
]
| Python | MIT License | marshmallow-code/apispec | flake8 compat |
393,992 | 17.11.2017 11:07:07 | -3,600 | 7544c9bec01da89ecf0b2091bc43c76af1bb0f17 | swagger auto reference schemas: references on schema addition instead schema reading | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/__init__.py",
"new_path": "apispec/ext/marshmallow/__init__.py",
"diff": "@@ -34,6 +34,55 @@ from . import swagger\nNAME = 'apispec.ext.marshmallow'\n+def get_schema_instance(schema):\n+ \"\"\"Return schema instance for given schema (instance or class)\n+ :param schema: instance or class of marshmallow.Schema\n+ :return: schema instance of given schema (instance or class)\n+ \"\"\"\n+ if isinstance(schema, type):\n+ return schema()\n+ else:\n+ return schema\n+\n+\n+def get_schema_class(schema):\n+ \"\"\"Return schema class for given schema (instance or class)\n+ :param schema: instance or class of marshmallow.Schema\n+ :return: schema class of given schema (instance or class)\n+ \"\"\"\n+ if isinstance(schema, type):\n+ return schema\n+ else:\n+ return type(schema)\n+\n+\n+def inspect_schema_for_auto_referencing(spec, original_schema_instance):\n+ \"\"\"Parse given schema instance and reference eventual nested schemas\n+ :param spec: apispec.core.APISpec instance\n+ :param original_schema_instance: schema to parse\n+ \"\"\"\n+ # spec.schema_name_resolver must be provided to use this function\n+ assert spec.schema_name_resolver\n+\n+ plug = spec.plugins[NAME]\n+ if 'refs' not in plug:\n+ plug['refs'] = {}\n+\n+ for field_name, field in original_schema_instance.fields.items():\n+ if isinstance(field, marshmallow.fields.Nested):\n+ nested_schema_class = get_schema_class(field.schema)\n+\n+ if nested_schema_class not in plug['refs']:\n+ definition_name = spec.schema_name_resolver(\n+ nested_schema_class,\n+ )\n+ if definition_name:\n+ spec.definition(\n+ definition_name,\n+ schema=nested_schema_class,\n+ )\n+\n+\ndef schema_definition_helper(spec, name, schema, **kwargs):\n\"\"\"Definition helper that allows using a marshmallow\n:class:`Schema <marshmallow.Schema>` to provide OpenAPI\n@@ -42,19 +91,22 @@ def schema_definition_helper(spec, name, schema, **kwargs):\n:param type|Schema schema: A marshmallow Schema class or instance.\n\"\"\"\n- if isinstance(schema, type):\n- schema_cls = schema\n- schema_instance = schema()\n- else:\n- schema_cls = type(schema)\n- schema_instance = schema\n+ schema_cls = get_schema_class(schema)\n+ schema_instance = get_schema_instance(schema)\n# Store registered refs, keyed by Schema class\nplug = spec.plugins[NAME]\nif 'refs' not in plug:\nplug['refs'] = {}\nplug['refs'][schema_cls] = name\n- return swagger.schema2jsonschema(schema_instance, spec=spec, name=name)\n+\n+ json_schema = swagger.schema2jsonschema(schema_instance, spec=spec, name=name)\n+\n+ # Auto reference schema if spec.schema_name_resolver\n+ if spec and spec.schema_name_resolver:\n+ inspect_schema_for_auto_referencing(spec, schema_instance)\n+\n+ return json_schema\ndef schema_path_helper(spec, view=None, **kwargs):\n@@ -163,13 +215,6 @@ def resolve_schema_dict(spec, schema, dump=True, use_instances=False):\nelse:\nschema_cls = resolve_schema_cls(schema)\n- # Auto reference schema if available\n- if schema_cls not in plug.get('refs', {}):\n- if spec and spec.schema_name_resolver:\n- definition_name = spec.schema_name_resolver(schema_cls)\n- if definition_name:\n- spec.definition(definition_name, schema=schema)\n-\nif schema_cls in plug.get('refs', {}):\nref_schema = {'$ref': '#/definitions/{0}'.format(plug['refs'][schema_cls])}\nif getattr(schema, 'many', False):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_marshmallow.py",
"new_path": "tests/test_ext_marshmallow.py",
"diff": "@@ -63,17 +63,11 @@ class TestDefinitionHelper:\n}\n})\n- # Other shemas not yet referenced\n- assert 1 == len(spec._definitions)\n+ assert 3 == len(spec._definitions)\n- spec_dict = spec.to_dict()\n- assert spec_dict.get('definitions')\n- assert 'analysis' in spec_dict['definitions']\n- # Inspect/Read objects will trigger auto reference\n- json.dumps(spec_dict)\n- # Other shema is now referenced\n- assert 2 == len(spec._definitions)\n- assert 'SampleSchema' in spec_dict['definitions']\n+ assert 'analysis' in spec._definitions\n+ assert 'SampleSchema' in spec._definitions\n+ assert 'RunSchema' in spec._definitions\[email protected]('schema', [AnalysisSchema, AnalysisSchema()])\ndef test_resolve_schema_dict_auto_reference_return_none(self, schema):\n"
}
]
| Python | MIT License | marshmallow-code/apispec | swagger auto reference schemas: references on schema addition instead schema reading |
393,992 | 07.12.2017 11:17:23 | -3,600 | f1e1a1c4e18cf6abb1166f8c73a1aa350e445f49 | auto-refencement: auto-reference to when schema nested in list | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/__init__.py",
"new_path": "apispec/ext/marshmallow/__init__.py",
"diff": "@@ -69,10 +69,16 @@ def inspect_schema_for_auto_referencing(spec, original_schema_instance):\nplug['refs'] = {}\nfor field_name, field in original_schema_instance.fields.items():\n+ nested_schema_class = None\n+\nif isinstance(field, marshmallow.fields.Nested):\nnested_schema_class = get_schema_class(field.schema)\n- if nested_schema_class not in plug['refs']:\n+ elif isinstance(field, marshmallow.fields.List) \\\n+ and isinstance(field.container, marshmallow.fields.Nested):\n+ nested_schema_class = get_schema_class(field.container.schema)\n+\n+ if nested_schema_class and nested_schema_class not in plug['refs']:\ndefinition_name = spec.schema_name_resolver(\nnested_schema_class,\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/schemas.py",
"new_path": "tests/schemas.py",
"diff": "@@ -20,6 +20,10 @@ class AnalysisSchema(Schema):\nsample = fields.Nested(SampleSchema)\n+class AnalysisWithListSchema(Schema):\n+ samples = fields.List(fields.Nested(SampleSchema))\n+\n+\nclass PatternedObjectSchema(Schema):\ncount = fields.Int(dump_only=True, **{'x-count': 1})\ncount2 = fields.Int(dump_only=True, x_count2=2)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_marshmallow.py",
"new_path": "tests/test_ext_marshmallow.py",
"diff": "@@ -6,8 +6,9 @@ from marshmallow.fields import Field, DateTime\nfrom apispec import APISpec\nfrom apispec.ext.marshmallow import swagger\n-from .schemas import PetSchema, AnalysisSchema, SampleSchema, RunSchema, SelfReferencingSchema,\\\n- OrderedSchema, PatternedObjectSchema, DefaultCallableSchema\n+from .schemas import PetSchema, AnalysisSchema, SampleSchema, RunSchema, \\\n+ SelfReferencingSchema, OrderedSchema, PatternedObjectSchema, \\\n+ DefaultCallableSchema, AnalysisWithListSchema\[email protected]()\n@@ -69,6 +70,40 @@ class TestDefinitionHelper:\nassert 'SampleSchema' in spec._definitions\nassert 'RunSchema' in spec._definitions\n+ @pytest.mark.parametrize('schema', [AnalysisWithListSchema, AnalysisWithListSchema()])\n+ def test_resolve_schema_dict_auto_reference_in_list(self, schema):\n+ def resolver(schema):\n+ return schema.__name__\n+ spec = APISpec(\n+ title='Test auto-reference',\n+ version='2.0',\n+ description='Test auto-reference',\n+ plugins=(\n+ 'apispec.ext.marshmallow',\n+ ),\n+ schema_name_resolver=resolver,\n+ )\n+ assert {} == spec._definitions\n+\n+ spec.definition('analysis', schema=schema)\n+ spec.add_path('/test', operations={\n+ 'get': {\n+ 'responses': {\n+ '200': {\n+ 'schema': {\n+ '$ref': '#/definitions/analysis'\n+ }\n+ }\n+ }\n+ }\n+ })\n+\n+ assert 3 == len(spec._definitions)\n+\n+ assert 'analysis' in spec._definitions\n+ assert 'SampleSchema' in spec._definitions\n+ assert 'RunSchema' in spec._definitions\n+\[email protected]('schema', [AnalysisSchema, AnalysisSchema()])\ndef test_resolve_schema_dict_auto_reference_return_none(self, schema):\n# this resolver return None\n"
}
]
| Python | MIT License | marshmallow-code/apispec | auto-refencement: auto-reference to when schema nested in list |
393,992 | 07.12.2017 11:34:23 | -3,600 | 61939ff20486dcc18359416d41ae664d89d8e1e0 | restore original version of apispec (commit error, it was for our fork) | [
{
"change_type": "MODIFY",
"old_path": "setup.py",
"new_path": "setup.py",
"diff": "@@ -34,7 +34,7 @@ def read(fname):\nsetup(\nname='apispec',\n- version='0.25.4-algoo',\n+ version=__version__,\ndescription='A pluggable API specification generator. Currently supports the '\n'OpenAPI specification (f.k.a. Swagger 2.0).',\nlong_description=read('README.rst'),\n"
}
]
| Python | MIT License | marshmallow-code/apispec | restore original version of apispec (commit error, it was for our fork) |
394,000 | 04.12.2017 21:35:57 | 18,000 | b4977a8218105672c5b67b76fc327f2e0e7e93cd | adds optional config param for OpenAPI version 3
This is an intial attempt to add basic support for OpenApi 3.
Based on the value of the openapi_version field, the APISpec.todict
places schemas either directly in "definitions" (v2) or in
"components/schemas" (v3)
References for nested Marshmallow schemas are also handled
See | [
{
"change_type": "MODIFY",
"old_path": "apispec/core.py",
"new_path": "apispec/core.py",
"diff": "@@ -16,7 +16,7 @@ VALID_METHODS = [\n'options',\n]\n-OPENAPI_VERSION = SWAGGER_VERSION = '2.0'\n+OPENAPI_VERSIONS = ('2.0', '3.0.0')\ndef clean_operations(operations):\n@@ -109,6 +109,7 @@ class APISpec(object):\nplugins=(),\ninfo=None,\nschema_name_resolver=None,\n+ openapi_version='2.0',\n**options\n):\nself.info = {\n@@ -116,6 +117,13 @@ class APISpec(object):\n'version': version,\n}\nself.info.update(info or {})\n+\n+ if openapi_version not in OPENAPI_VERSIONS:\n+ raise APISpecError(\n+ 'Not a valid OpenAPI version number: {}'.format(openapi_version)\n+ )\n+ self.openapi_version = openapi_version\n+\nself.options = options\nself.schema_name_resolver = schema_name_resolver\n# Metadata\n@@ -136,13 +144,20 @@ class APISpec(object):\ndef to_dict(self):\nret = {\n- 'swagger': OPENAPI_VERSION,\n'info': self.info,\n- 'definitions': self._definitions,\n- 'parameters': self._parameters,\n'paths': self._paths,\n'tags': self._tags\n}\n+\n+ if self.openapi_version == '2.0':\n+ ret['swagger'] = self.openapi_version\n+ ret['definitions'] = self._definitions\n+ ret['parameters'] = self._parameters\n+\n+ elif self.openapi_version == '3.0.0':\n+ ret['openapi'] = self.openapi_version\n+ ret['components'] = {'schemas': self._definitions}\n+\nret.update(self.options)\nreturn ret\n"
},
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/__init__.py",
"new_path": "apispec/ext/marshmallow/__init__.py",
"diff": "@@ -222,7 +222,9 @@ def resolve_schema_dict(spec, schema, dump=True, use_instances=False):\nschema_cls = resolve_schema_cls(schema)\nif schema_cls in plug.get('refs', {}):\n- ref_schema = {'$ref': '#/definitions/{0}'.format(plug['refs'][schema_cls])}\n+ ref_path = swagger.get_ref_path(spec.openapi_version)\n+ ref_schema = {'$ref': '#/{0}/{1}'.format(ref_path,\n+ plug['refs'][schema_cls])}\nif getattr(schema, 'many', False):\nreturn {\n'type': 'array',\n"
},
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/swagger.py",
"new_path": "apispec/ext/marshmallow/swagger.py",
"diff": "@@ -308,7 +308,9 @@ def field2property(field, spec=None, use_refs=True, dump=True, name=None):\nraise ValueError('Must pass `name` argument for self-referencing Nested fields.')\n# We need to use the `name` argument when the field is self-referencing and\n# unbound (doesn't have `parent` set) because we can't access field.schema\n- ref_name = '#/definitions/{name}'.format(name=name)\n+ ref_path = get_ref_path(spec.openapi_version)\n+ ref_name = '#/{ref_path}/{name}'.format(ref_path=ref_path,\n+ name=name)\nref_schema = {'$ref': ref_name}\nif field.many:\nret['type'] = 'array'\n@@ -578,6 +580,16 @@ def fields2jsonschema(fields, schema=None, spec=None, use_refs=True, dump=True,\nreturn jsonschema\n+\n+def get_ref_path(openapi_version):\n+ \"\"\"Return the path for references based on the openapi version\n+\n+ :param openapi_version|string: the open api version number\n+ \"\"\"\n+ ref_paths = {'2.0': 'definitions',\n+ '3.0.0': 'components/schemas'}\n+ return ref_paths[openapi_version]\n+\n__location_map__ = {\n'query': 'query',\n'querystring': 'query',\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_core.py",
"new_path": "tests/test_core.py",
"diff": "@@ -21,12 +21,39 @@ def spec():\nsecurity=[{'apiKey': []}],\n)\[email protected]()\n+def spec_3():\n+ return APISpec(\n+ title='Swagger Petstore',\n+ version='1.0.0',\n+ info={'description': description},\n+ security=[{'apiKey': []}],\n+ openapi_version='3.0.0'\n+ )\n+\n+\n+class TestAPISpecInit:\n+\n+ def test_raises_wrong_apispec_version(self):\n+ with pytest.raises(APISpecError) as excinfo:\n+ APISpec(\n+ 'Swagger Petstore',\n+ version='1.0.0',\n+ info={'description': description},\n+ security=[{'apiKey': []}],\n+ openapi_version='no version'\n+ )\n+ assert 'Not a valid OpenAPI version number:' in str(excinfo)\n+\nclass TestMetadata:\ndef test_swagger_version(self, spec):\nassert spec.to_dict()['swagger'] == '2.0'\n+ def test_openapi_version_3(self, spec_3):\n+ assert spec_3.to_dict()['openapi'] == '3.0.0'\n+\ndef test_swagger_metadata(self, spec):\nmetadata = spec.to_dict()\nassert metadata['security'] == [{'apiKey': []}]\n@@ -61,6 +88,12 @@ class TestDefinitions:\nassert 'Pet' in defs_json\nassert defs_json['Pet']['properties'] == self.properties\n+ def test_definition_3(self, spec_3):\n+ spec_3.definition('Pet', properties=self.properties)\n+ schemas = spec_3.to_dict()['components']['schemas']\n+ assert 'Pet' in schemas\n+ assert schemas['Pet']['properties'] == self.properties\n+\ndef test_definition_description(self, spec):\nmodel_description = 'An animal which lives with humans.'\nspec.definition('Pet', properties=self.properties, description=model_description)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_swagger.py",
"new_path": "tests/test_swagger.py",
"diff": "@@ -560,12 +560,12 @@ class TestNesting:\ndef test_field2property_nested_self(self, spec):\nself_nesting = fields.Nested('self')\n- res = swagger.field2property(self_nesting, name='Foo')\n+ res = swagger.field2property(self_nesting, spec=spec, name='Foo')\nassert res == {'$ref': '#/definitions/Foo'}\ndef test_field2property_nested_self_many(self, spec):\nself_nesting = fields.Nested('self', many=True)\n- res = swagger.field2property(self_nesting, name='Foo')\n+ res = swagger.field2property(self_nesting, spec=spec, name='Foo')\nassert res == {'type': 'array', 'items': {'$ref': '#/definitions/Foo'}}\ndef test_field2property_nested_self_ref_with_meta(self, spec):\n"
}
]
| Python | MIT License | marshmallow-code/apispec | adds optional config param for OpenAPI version 3
This is an intial attempt to add basic support for OpenApi 3.
Based on the value of the openapi_version field, the APISpec.todict
places schemas either directly in "definitions" (v2) or in
"components/schemas" (v3)
References for nested Marshmallow schemas are also handled
See https://blog.readme.io/an-example-filled-guide-to-swagger-3-2/ |
394,000 | 05.12.2017 13:14:31 | 18,000 | 1d221336d153b54ec28e47dbe6f5bf55fee78343 | adds parameters the appropriate location based on OpenAPI version | [
{
"change_type": "MODIFY",
"old_path": "apispec/core.py",
"new_path": "apispec/core.py",
"diff": "@@ -19,7 +19,7 @@ VALID_METHODS = [\nOPENAPI_VERSIONS = ('2.0', '3.0.0')\n-def clean_operations(operations):\n+def clean_operations(operations, openapi_version):\n\"\"\"Ensure that all parameters with \"in\" equal to \"path\" are also required\nas required by the OpenAPI specification, as well as normalizing any\nreferences to global parameters.\n@@ -27,9 +27,19 @@ def clean_operations(operations):\nSee https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameterObject.\n:param dict operations: Dict mapping status codes to operations\n+ :param str openapi_version: The version of the OpenAPI standard to use.\n+ Supported values are '2.0', and '3.0.0'.\n\"\"\"\n- def get_ref(x):\n- return x if isinstance(x, dict) else {'$ref': '#/parameters/' + x}\n+ def get_ref(x, openapi_version):\n+ if isinstance(x, dict):\n+ return x\n+\n+ ref_paths = {\n+ '2.0': 'parameters',\n+ '3.0.0': 'components/parameters',\n+ }\n+ ref_path = ref_paths[openapi_version]\n+ return {'$ref': '#/{0}/{1}'.format(ref_path, x)}\nfor operation in (operations or {}).values():\nif 'parameters' in operation:\n@@ -38,7 +48,8 @@ def clean_operations(operations):\nif (isinstance(parameter, dict) and\n'in' in parameter and parameter['in'] == 'path'):\nparameter['required'] = True\n- operation['parameters'] = [get_ref(p) for p in parameters]\n+ operation['parameters'] = [get_ref(p, openapi_version)\n+ for p in parameters]\nclass Path(dict):\n@@ -50,12 +61,14 @@ class Path(dict):\n:param str method: The HTTP method.\n:param dict operation: The operation object, as a `dict`. See\nhttps://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#operationObject\n+ :param str openapi_version: The version of the OpenAPI standard to use.\n+ Supported values are '2.0', and '3.0.0'.\n\"\"\"\n- def __init__(self, path=None, operations=None, **kwargs):\n+ def __init__(self, path=None, operations=None, openapi_version='2.0', **kwargs):\nself.path = path\noperations = operations or {}\n- clean_operations(operations)\n+ clean_operations(operations, openapi_version)\ninvalid = {key for key in\nset(iterkeys(operations)) - set(VALID_METHODS)\nif not key.startswith('x-')}\n@@ -156,7 +169,10 @@ class APISpec(object):\nelif self.openapi_version == '3.0.0':\nret['openapi'] = self.openapi_version\n- ret['components'] = {'schemas': self._definitions}\n+ ret['components'] = {\n+ 'schemas': self._definitions,\n+ 'parameters': self._parameters,\n+ }\nret.update(self.options)\nreturn ret\n@@ -205,7 +221,9 @@ class APISpec(object):\nif isinstance(path, Path):\npath.path = p\nelse:\n- path = Path(path=p, operations=operations)\n+ path = Path(path=p,\n+ operations=operations,\n+ openapi_version=self.openapi_version)\n# Execute plugins' helpers\nfor func in self._path_helpers:\ntry:\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_core.py",
"new_path": "tests/test_core.py",
"diff": "@@ -295,6 +295,25 @@ class TestPath:\nassert p['parameters'][0] == {'$ref': '#/parameters/test_parameter'}\nassert route_spec['parameters'][0] == metadata['parameters']['test_parameter']\n+ def test_add_parameters_3(self, spec_3):\n+ route_spec = self.paths['/pet/{petId}']['get']\n+\n+ spec_3.add_parameter('test_parameter', 'path', **route_spec['parameters'][0])\n+\n+ spec_3.add_path(\n+ path='/pet/{petId}',\n+ operations=dict(\n+ get=dict(\n+ parameters=['test_parameter'],\n+ )\n+ )\n+ )\n+\n+ metadata = spec_3.to_dict()\n+ p = spec_3._paths['/pet/{petId}']['get']\n+\n+ assert p['parameters'][0] == {'$ref': '#/components/parameters/test_parameter'}\n+ assert route_spec['parameters'][0] == metadata['components']['parameters']['test_parameter']\nclass TestPlugins:\n"
}
]
| Python | MIT License | marshmallow-code/apispec | adds parameters the appropriate location based on OpenAPI version |
394,000 | 11.12.2017 22:32:22 | 18,000 | acf366ea1dc4e1586fa9b51569fa3faabc6a25bc | Validates OpenAPI version with distutils.version | [
{
"change_type": "MODIFY",
"old_path": "apispec/core.py",
"new_path": "apispec/core.py",
"diff": "\"\"\"Core apispec classes and functions.\"\"\"\nimport re\nfrom collections import OrderedDict\n+from distutils import version\nfrom apispec.compat import iterkeys\nfrom .exceptions import APISpecError, PluginError\n@@ -16,8 +17,6 @@ VALID_METHODS = [\n'options',\n]\n-OPENAPI_VERSIONS = ('2.0', '3.0.0')\n-\ndef clean_operations(operations, openapi_version):\n\"\"\"Ensure that all parameters with \"in\" equal to \"path\" are also required\n@@ -131,11 +130,7 @@ class APISpec(object):\n}\nself.info.update(info or {})\n- if openapi_version not in OPENAPI_VERSIONS:\n- raise APISpecError(\n- 'Not a valid OpenAPI version number: {}'.format(openapi_version)\n- )\n- self.openapi_version = openapi_version\n+ self.openapi_version = validate_openapi_version(openapi_version)\nself.options = options\nself.schema_name_resolver = schema_name_resolver\n@@ -370,3 +365,21 @@ class APISpec(object):\nif method not in self._response_helpers:\nself._response_helpers[method] = {}\nself._response_helpers[method].setdefault(status_code, []).append(func)\n+\n+def validate_openapi_version(openapi_version_str):\n+ \"\"\"Function to validate the version of the OpenAPI passed into APISpec\n+\n+ :param str openapi_version_str: the string version of the desired OpenAPI\n+ version used in the output\n+ \"\"\"\n+ min_inclusive_version = version.LooseVersion('2.0')\n+ max_exclusive_version = version.LooseVersion('4.0')\n+\n+ openapi_version = version.LooseVersion(openapi_version_str)\n+\n+ if not min_inclusive_version <= openapi_version < max_exclusive_version:\n+ raise APISpecError(\n+ 'Not a valid OpenAPI version number: {}'.format(openapi_version)\n+ )\n+\n+ return openapi_version.vstring\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Validates OpenAPI version with distutils.version |
394,000 | 11.12.2017 23:17:57 | 18,000 | 79cdbe29c136ec57c892f2b8ed23b7a1171f6203 | changes logic to use only the OpenAPI major verion
Now minor version numbers are used to determining the
placement of schemas and paramaters in the dictionary | [
{
"change_type": "MODIFY",
"old_path": "apispec/core.py",
"new_path": "apispec/core.py",
"diff": "@@ -18,7 +18,7 @@ VALID_METHODS = [\n]\n-def clean_operations(operations, openapi_version):\n+def clean_operations(operations, openapi_major_version):\n\"\"\"Ensure that all parameters with \"in\" equal to \"path\" are also required\nas required by the OpenAPI specification, as well as normalizing any\nreferences to global parameters.\n@@ -26,18 +26,18 @@ def clean_operations(operations, openapi_version):\nSee https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameterObject.\n:param dict operations: Dict mapping status codes to operations\n- :param str openapi_version: The version of the OpenAPI standard to use.\n- Supported values are '2.0', and '3.0.0'.\n+ :param int openapi_major_version: The major version of the OpenAPI standard\n+ to use. Supported values are 2 and 3.\n\"\"\"\n- def get_ref(x, openapi_version):\n+ def get_ref(x, openapi_major_version):\nif isinstance(x, dict):\nreturn x\nref_paths = {\n- '2.0': 'parameters',\n- '3.0.0': 'components/parameters',\n+ 2: 'parameters',\n+ 3: 'components/parameters',\n}\n- ref_path = ref_paths[openapi_version]\n+ ref_path = ref_paths[openapi_major_version]\nreturn {'$ref': '#/{0}/{1}'.format(ref_path, x)}\nfor operation in (operations or {}).values():\n@@ -47,7 +47,7 @@ def clean_operations(operations, openapi_version):\nif (isinstance(parameter, dict) and\n'in' in parameter and parameter['in'] == 'path'):\nparameter['required'] = True\n- operation['parameters'] = [get_ref(p, openapi_version)\n+ operation['parameters'] = [get_ref(p, openapi_major_version)\nfor p in parameters]\n@@ -61,13 +61,15 @@ class Path(dict):\n:param dict operation: The operation object, as a `dict`. See\nhttps://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#operationObject\n:param str openapi_version: The version of the OpenAPI standard to use.\n- Supported values are '2.0', and '3.0.0'.\n+ Should be in the form '2.x' or '3.x.x' to comply with the OpenAPI\n+ standard.\n\"\"\"\ndef __init__(self, path=None, operations=None, openapi_version='2.0', **kwargs):\nself.path = path\noperations = operations or {}\n- clean_operations(operations, openapi_version)\n+ openapi_version = validate_openapi_version(openapi_version)\n+ clean_operations(operations, openapi_version.version[0])\ninvalid = {key for key in\nset(iterkeys(operations)) - set(VALID_METHODS)\nif not key.startswith('x-')}\n@@ -109,7 +111,9 @@ class APISpec(object):\ndef schema_name_resolver(schema):\nreturn schema.__name__\n-\n+ :param str openapi_version: The version of the OpenAPI standard to use.\n+ Should be in the form '2.x' or '3.x.x' to comply with the OpenAPI\n+ standard.\n:param \\*\\*dict options: Optional top-level keys\nSee https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#swagger-object\n\"\"\"\n@@ -157,13 +161,13 @@ class APISpec(object):\n'tags': self._tags\n}\n- if self.openapi_version == '2.0':\n- ret['swagger'] = self.openapi_version\n+ if self.openapi_version.version[0] == 2:\n+ ret['swagger'] = self.openapi_version.vstring\nret['definitions'] = self._definitions\nret['parameters'] = self._parameters\n- elif self.openapi_version == '3.0.0':\n- ret['openapi'] = self.openapi_version\n+ elif self.openapi_version.version[0] == 3:\n+ ret['openapi'] = self.openapi_version.vstring\nret['components'] = {\n'schemas': self._definitions,\n'parameters': self._parameters,\n@@ -218,7 +222,7 @@ class APISpec(object):\nelse:\npath = Path(path=p,\noperations=operations,\n- openapi_version=self.openapi_version)\n+ openapi_version=self.openapi_version.vstring)\n# Execute plugins' helpers\nfor func in self._path_helpers:\ntry:\n@@ -382,4 +386,4 @@ def validate_openapi_version(openapi_version_str):\n'Not a valid OpenAPI version number: {}'.format(openapi_version)\n)\n- return openapi_version.vstring\n+ return openapi_version\n"
},
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/__init__.py",
"new_path": "apispec/ext/marshmallow/__init__.py",
"diff": "@@ -222,7 +222,7 @@ def resolve_schema_dict(spec, schema, dump=True, use_instances=False):\nschema_cls = resolve_schema_cls(schema)\nif schema_cls in plug.get('refs', {}):\n- ref_path = swagger.get_ref_path(spec.openapi_version)\n+ ref_path = swagger.get_ref_path(spec.openapi_version.version[0])\nref_schema = {'$ref': '#/{0}/{1}'.format(ref_path,\nplug['refs'][schema_cls])}\nif getattr(schema, 'many', False):\n"
},
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/swagger.py",
"new_path": "apispec/ext/marshmallow/swagger.py",
"diff": "@@ -308,7 +308,7 @@ def field2property(field, spec=None, use_refs=True, dump=True, name=None):\nraise ValueError('Must pass `name` argument for self-referencing Nested fields.')\n# We need to use the `name` argument when the field is self-referencing and\n# unbound (doesn't have `parent` set) because we can't access field.schema\n- ref_path = get_ref_path(spec.openapi_version)\n+ ref_path = get_ref_path(spec.openapi_version.version[0])\nref_name = '#/{ref_path}/{name}'.format(ref_path=ref_path,\nname=name)\nref_schema = {'$ref': ref_name}\n@@ -581,14 +581,15 @@ def fields2jsonschema(fields, schema=None, spec=None, use_refs=True, dump=True,\nreturn jsonschema\n-def get_ref_path(openapi_version):\n+def get_ref_path(openapi_major_version):\n\"\"\"Return the path for references based on the openapi version\n- :param openapi_version|string: the open api version number\n+ :param int openapi_major_version: The major version of the OpenAPI standard\n+ to use. Supported values are 2 and 3.\n\"\"\"\n- ref_paths = {'2.0': 'definitions',\n- '3.0.0': 'components/schemas'}\n- return ref_paths[openapi_version]\n+ ref_paths = {2: 'definitions',\n+ 3: 'components/schemas'}\n+ return ref_paths[openapi_major_version]\n__location_map__ = {\n'query': 'query',\n"
}
]
| Python | MIT License | marshmallow-code/apispec | changes logic to use only the OpenAPI major verion
Now minor version numbers are used to determining the
placement of schemas and paramaters in the dictionary |
394,000 | 11.12.2017 23:48:52 | 18,000 | 13f01667c9c50da31bb6b68730836da9aab68aae | fixes test on python 3 | [
{
"change_type": "MODIFY",
"old_path": "tests/test_core.py",
"new_path": "tests/test_core.py",
"diff": "@@ -41,7 +41,7 @@ class TestAPISpecInit:\nversion='1.0.0',\ninfo={'description': description},\nsecurity=[{'apiKey': []}],\n- openapi_version='no version'\n+ openapi_version='4.0' # 4.0 is not supported\n)\nassert 'Not a valid OpenAPI version number:' in str(excinfo)\n"
}
]
| Python | MIT License | marshmallow-code/apispec | fixes test on python 3 |
394,000 | 02.01.2018 23:26:14 | 18,000 | 129b9c1878b08eccc8a204d7f1dc4c343cfea8a3 | resolve schemas from requestBody and response objects | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/__init__.py",
"new_path": "apispec/ext/marshmallow/__init__.py",
"diff": "@@ -192,10 +192,10 @@ def schema_operation_resolver(spec, operations, **kwargs):\ncontinue\nif 'parameters' in operation:\noperation['parameters'] = resolve_parameters(spec, operation['parameters'])\n+ if 'requestBody' in operation: # OpenAPI 3\n+ resolve_schema_in_request_body(spec, operation['requestBody'])\nfor response in operation.get('responses', {}).values():\n- if 'schema' in response:\n- response['schema'] = resolve_schema_dict(spec, response['schema'])\n-\n+ resolve_schema_in_response(spec, response)\ndef resolve_parameters(spec, parameters):\nresolved = []\n@@ -210,6 +210,32 @@ def resolve_parameters(spec, parameters):\nreturn resolved\n+def resolve_schema_in_request_body(spec, request_body):\n+ \"\"\"Function to resolve a schema in a requestBody object - modifies then\n+ response dict to convert Marshmallow Schema object or class into dict\n+\n+ :param APISpec spec: `APISpec` containing refs.\n+ \"\"\"\n+ content = request_body['content']\n+ for content_type in content:\n+ schema = content[content_type]['schema']\n+ content[content_type]['schema'] = resolve_schema_dict(spec, schema)\n+\n+\n+def resolve_schema_in_response(spec, response):\n+ \"\"\"Function to resolve a schema in a response - modifies the response\n+ dict to convert Marshmallow Schema object or class into dict\n+\n+ :param APISpec spec: `APISpec` containing refs.\n+ :param dict response: the response dictionary that may contain a schema\n+ \"\"\"\n+ if 'schema' in response: # OpenAPI 2\n+ response['schema'] = resolve_schema_dict(spec, response['schema'])\n+ if 'content' in response: # OpenAPI 3\n+ for content_type in response['content']:\n+ schema = response['content'][content_type]['schema']\n+ response['content'][content_type]['schema'] = resolve_schema_dict(spec, schema)\n+\ndef resolve_schema_dict(spec, schema, dump=True, use_instances=False):\nif isinstance(schema, dict):\nif (schema.get('type') == 'array' and 'items' in schema):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_marshmallow.py",
"new_path": "tests/test_ext_marshmallow.py",
"diff": "@@ -11,20 +11,38 @@ from .schemas import PetSchema, AnalysisSchema, SampleSchema, RunSchema, \\\nDefaultCallableSchema, AnalysisWithListSchema\n+description = 'This is a sample Petstore server. You can find out more '\n+'about Swagger at <a href=\\\"http://swagger.wordnik.com\\\">http://swagger.wordnik.com</a> '\n+'or on irc.freenode.net, #swagger. For this sample, you can use the api '\n+'key \\\"special-key\\\" to test the authorization filters'\n+\n+\[email protected]()\ndef spec():\nreturn APISpec(\ntitle='Swagger Petstore',\nversion='1.0.0',\n- description='This is a sample Petstore server. You can find out more '\n- 'about Swagger at <a href=\\\"http://swagger.wordnik.com\\\">http://swagger.wordnik.com</a> '\n- 'or on irc.freenode.net, #swagger. For this sample, you can use the api '\n- 'key \\\"special-key\\\" to test the authorization filters',\n+ description=description,\n+ plugins=[\n+ 'apispec.ext.marshmallow'\n+ ]\n+ )\n+\n+\[email protected]()\n+def spec_3():\n+ return APISpec(\n+ title='Swagger Petstore',\n+ version='1.0.0',\n+ info={'description': description},\n+ security=[{'apiKey': []}],\n+ openapi_version='3.0.0',\nplugins=[\n'apispec.ext.marshmallow'\n]\n)\n+\nclass TestDefinitionHelper:\[email protected]('schema', [PetSchema, PetSchema()])\n@@ -210,6 +228,35 @@ class TestOperationHelper:\nassert 'responses' in op\nassert op['responses'][200]['schema'] == swagger.schema2jsonschema(PetSchema)\n+ def test_schema_v3(self, spec_3):\n+ def pet_view():\n+ return '...'\n+\n+ spec_3.add_path(\n+ path='/pet',\n+ view=pet_view,\n+ operations={\n+ 'get': {\n+ 'responses': {\n+ 200: {\n+ 'content': {\n+ 'application/json': {\n+ 'schema': PetSchema\n+ }\n+ }\n+ }\n+ }\n+ }\n+ }\n+ )\n+ p = spec_3._paths['/pet']\n+ assert 'get' in p\n+ op = p['get']\n+ assert 'responses' in op\n+\n+ resolved_schema = op['responses'][200]['content']['application/json']['schema']\n+ assert resolved_schema == swagger.schema2jsonschema(PetSchema)\n+\ndef test_schema_in_docstring(self, spec):\ndef pet_view():\n@@ -241,6 +288,46 @@ class TestOperationHelper:\nassert post['responses'][201]['schema'] == swagger.schema2jsonschema(PetSchema)\nassert post['responses'][201]['description'] == 'successful operation'\n+ def test_schema_in_docstring_v3(self, spec_3):\n+\n+ def pet_view():\n+ \"\"\"Not much to see here.\n+\n+ ---\n+ get:\n+ responses:\n+ 200:\n+ content:\n+ application/json:\n+ schema: tests.schemas.PetSchema\n+ description: successful operation\n+ post:\n+ responses:\n+ 201:\n+ content:\n+ application/json:\n+ schema: tests.schemas.PetSchema\n+ description: successful operation\n+ \"\"\"\n+ return '...'\n+\n+ spec_3.add_path(path='/pet', view=pet_view)\n+ p = spec_3._paths['/pet']\n+ assert 'get' in p\n+ get = p['get']\n+ assert 'responses' in get\n+\n+ resolved_schema = get['responses'][200]['content']['application/json']['schema']\n+ assert resolved_schema == swagger.schema2jsonschema(PetSchema)\n+\n+ assert get['responses'][200]['description'] == 'successful operation'\n+ post = p['post']\n+ assert 'responses' in post\n+\n+ resolved_schema = post['responses'][201]['content']['application/json']['schema']\n+ assert resolved_schema == swagger.schema2jsonschema(PetSchema)\n+ assert post['responses'][201]['description'] == 'successful operation'\n+\ndef test_schema_in_docstring_expand_parameters(self, spec):\ndef pet_view():\n@@ -319,6 +406,26 @@ class TestOperationHelper:\nassert len(post['parameters']) == 1\nassert post['parameters'][0]['schema']['$ref'] == '#/definitions/Pet'\n+ def test_schema_in_request_body(self, spec_3):\n+ def pet_view():\n+ \"\"\"Not much to see here.\n+\n+ ---\n+ post:\n+ requestBody:\n+ content:\n+ application/json:\n+ schema: tests.schemas.PetSchema\n+ \"\"\"\n+ return '...'\n+ spec_3.definition('Pet', schema=PetSchema)\n+ spec_3.add_path(path='/pet', view=pet_view)\n+ p = spec_3._paths['/pet']\n+ assert 'post' in p\n+ post = p['post']\n+ schema_ref = post['requestBody']['content']['application/json']['schema']\n+ assert schema_ref == {'$ref': '#/components/schemas/Pet'}\n+\ndef test_schema_array_in_docstring_uses_ref_if_available(self, spec):\nspec.definition('Pet', schema=PetSchema)\n"
}
]
| Python | MIT License | marshmallow-code/apispec | resolve schemas from requestBody and response objects |
394,000 | 03.01.2018 11:36:45 | 18,000 | 3731f31bb4b311e71e87d58666dd27c7997e1a68 | adds support for validating OpenAPI 3 specs
Switches to using npm package check_api, which is a wrapper around
several API specification validators including OpenAPI 2 and 3.
swagger-tools is a depencency of check_api | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "@@ -8,7 +8,7 @@ python:\n- pypy\ninstall:\n- pip install -U .\n-- npm install -g swagger-tools\n+- npm install -g check_api\n- pip install -r dev-requirements.txt\nscript: invoke test\njobs:\n"
},
{
"change_type": "MODIFY",
"old_path": "CONTRIBUTING.rst",
"new_path": "CONTRIBUTING.rst",
"diff": "@@ -32,7 +32,7 @@ Setting Up for Local Development\n# After activating your virtualenv\n$ pip install -r dev-requirements.txt\n- $ npm install -g swagger-tools\n+ $ npm install -g check_api\n3. Install apispec in develop mode. ::\n"
},
{
"change_type": "MODIFY",
"old_path": "apispec/utils.py",
"new_path": "apispec/utils.py",
"diff": "\"\"\"Various utilities for parsing OpenAPI operations from docstrings and validating against\nthe OpenAPI spec.\n\"\"\"\n+import os\nimport re\nimport json\nimport tempfile\n@@ -85,18 +86,19 @@ def load_operations_from_docstring(docstring):\ndef validate_swagger(spec):\n\"\"\"Validate the output of an :class:`APISpec` object.\n- Note: Requires installing the node package `swagger-tools`.\n+ Note: Requires installing the node package `check_api`.\n:raise: SwaggerError if validation fails.\n\"\"\"\nwith tempfile.NamedTemporaryFile(mode='w') as fp:\njson.dump(spec.to_dict(), fp)\nfp.seek(0)\n+ shell = os.name == 'nt' # Set shell to true if running on Windows\ntry:\nsubprocess.check_output(\n- ['swagger-tools', 'validate', fp.name],\n+ ['check_api', fp.name],\nstderr=subprocess.STDOUT,\n- shell=True,\n+ shell=shell,\n)\nexcept subprocess.CalledProcessError as error:\nraise exceptions.SwaggerError(error.output.decode('utf-8'))\n"
}
]
| Python | MIT License | marshmallow-code/apispec | adds support for validating OpenAPI 3 specs
Switches to using npm package check_api, which is a wrapper around
several API specification validators including OpenAPI 2 and 3.
swagger-tools is a depencency of check_api |
394,000 | 03.01.2018 13:35:53 | 18,000 | 0e009056d30abbab408765f9ee777b37b7b54937 | adds a test for OpenAPI 3 spec | [
{
"change_type": "MODIFY",
"old_path": "tests/test_swagger.py",
"new_path": "tests/test_swagger.py",
"diff": "@@ -498,6 +498,9 @@ class PetSchema(Schema):\ncategory = fields.Nested(CategorySchema, many=True, ref='#/definitions/Category')\nname = fields.Str()\n+class PetSchemaV3(Schema):\n+ category = fields.Nested(CategorySchema, many=True, ref='#/components/schemas/Category')\n+ name = fields.Str()\nclass TestNesting:\n@@ -701,6 +704,78 @@ def test_swagger_tools_validate():\nexcept exceptions.SwaggerError as error:\npytest.fail(str(error))\n+def test_validate_v3():\n+ spec = APISpec(\n+ title='Pets',\n+ version='0.1',\n+ plugins=['apispec.ext.marshmallow'],\n+ openapi_version='3.0.0'\n+ )\n+\n+ spec.definition('Category', schema=CategorySchema)\n+ spec.definition('Pet', schema=PetSchemaV3)\n+\n+ spec.add_path(\n+ view=None,\n+ path='/category/{category_id}',\n+ operations={\n+ 'get': {\n+ 'parameters': [\n+ {'name': 'q',\n+ 'in': 'query',\n+ 'schema': {'type': 'string'}\n+ },\n+ {'name': 'category_id',\n+ 'in': 'path',\n+ 'required': True,\n+ 'schema': {'type': 'string'}\n+ },\n+ ], # + swagger.schema2parameters(PageSchema, default_in='query'),\n+ 'responses': {\n+ 200: {\n+ 'description': 'success',\n+ 'content': {\n+ 'application/json': {\n+ 'schema': PetSchemaV3,\n+ }\n+ }\n+ },\n+ },\n+ },\n+ 'post': {\n+ 'parameters': (\n+ [{'name': 'category_id',\n+ 'in': 'path',\n+ 'required': True,\n+ 'schema': {'type': 'string'}\n+ }\n+ ]\n+ ),\n+ 'requestBody': {\n+ 'content': {\n+ 'application/json': {\n+ 'schema': CategorySchema\n+ }\n+ }\n+ },\n+ 'responses': {\n+ 201: {\n+ 'description': 'created',\n+ 'content': {\n+ 'application/json': {\n+ 'schema': PetSchemaV3,\n+ }\n+ }\n+ },\n+ },\n+ }\n+ },\n+ )\n+ try:\n+ utils.validate_swagger(spec)\n+ except exceptions.SwaggerError as error:\n+ pytest.fail(str(error))\n+\nclass ValidationSchema(Schema):\nid = fields.Int(dump_only=True)\nrange = fields.Int(validate=validate.Range(min=1, max=10))\n"
}
]
| Python | MIT License | marshmallow-code/apispec | adds a test for OpenAPI 3 spec |
394,002 | 05.03.2018 23:17:21 | 21,600 | 27598407e7a8b61d7daeb4f68902c0eb7f84015f | pass additional parameter info | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/__init__.py",
"new_path": "apispec/ext/marshmallow/__init__.py",
"diff": "@@ -203,8 +203,9 @@ def resolve_parameters(spec, parameters):\nif not isinstance(parameter.get('schema', {}), dict):\nschema_cls = resolve_schema_cls(parameter['schema'])\nif issubclass(schema_cls, marshmallow.Schema) and 'in' in parameter:\n+ del parameter['schema']\nresolved += swagger.schema2parameters(\n- schema_cls, default_in=parameter['in'], spec=spec)\n+ schema_cls, default_in=parameter.pop('in'), spec=spec, **parameter)\ncontinue\nresolved.append(parameter)\nreturn resolved\n"
},
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/swagger.py",
"new_path": "apispec/ext/marshmallow/swagger.py",
"diff": "@@ -360,13 +360,12 @@ def schema2parameters(schema, **kwargs):\nraise ValueError(\n\"{0!r} doesn't have either `fields` or `_declared_fields`\".format(schema)\n)\n-\nreturn fields2parameters(fields, schema, **kwargs)\ndef fields2parameters(fields, schema=None, spec=None, use_refs=True,\ndefault_in='body', name='body', required=False,\n- use_instances=False):\n+ use_instances=False, description=None, **kwargs):\n\"\"\"Return an array of OpenAPI parameters given a mapping between field names and\n:class:`Field <marshmallow.Field>` objects. If `default_in` is \"body\", then return an array\nof a single parameter; else return an array of a parameter for each included field in\n@@ -383,12 +382,17 @@ def fields2parameters(fields, schema=None, spec=None, use_refs=True,\nelse:\nprop = fields2jsonschema(fields, spec=spec, use_refs=use_refs, dump=False)\n- return [{\n+ param = {\n'in': swagger_default_in,\n'required': required,\n'name': name,\n'schema': prop,\n- }]\n+ }\n+\n+ if description:\n+ param['description'] = description\n+\n+ return [param]\nassert not getattr(schema, 'many', False), \\\n\"Schemas with many=True are only supported for 'json' location (aka 'in: body')\"\n"
}
]
| Python | MIT License | marshmallow-code/apispec | pass additional parameter info |
393,976 | 04.05.2018 16:11:36 | -7,200 | 881213aaabb791aed549cd5b20c94a87d3755618 | Add handling for marshmallow Dict field type
Dict type resolves to object type with additionalProperties type derived from the 'values' field | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/swagger.py",
"new_path": "apispec/ext/marshmallow/swagger.py",
"diff": "@@ -379,6 +379,8 @@ def field2property(field, spec=None, use_refs=True, dump=True, name=None):\nret.update(schema2jsonschema(field.schema, dump=dump))\nelif isinstance(field, marshmallow.fields.List):\nret['items'] = field2property(field.container, spec=spec, use_refs=use_refs, dump=dump)\n+ elif isinstance(field, marshmallow.fields.Dict):\n+ ret['additionalProperties'] = field2property(field.metadata['values'], spec=spec, use_refs=use_refs, dump=dump)\n# Dasherize metadata that starts with x_\nmetadata = {\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Add handling for marshmallow Dict field type
Dict type resolves to object type with additionalProperties type derived from the 'values' field |
393,976 | 04.05.2018 16:16:53 | -7,200 | defbe0c4400d271bc660aea5664ad2c3150a0ab8 | add handling for lack of Dict values metadata | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/swagger.py",
"new_path": "apispec/ext/marshmallow/swagger.py",
"diff": "@@ -380,6 +380,7 @@ def field2property(field, spec=None, use_refs=True, dump=True, name=None):\nelif isinstance(field, marshmallow.fields.List):\nret['items'] = field2property(field.container, spec=spec, use_refs=use_refs, dump=dump)\nelif isinstance(field, marshmallow.fields.Dict):\n+ if 'values' in field.metadata:\nret['additionalProperties'] = field2property(field.metadata['values'], spec=spec, use_refs=use_refs, dump=dump)\n# Dasherize metadata that starts with x_\n"
}
]
| Python | MIT License | marshmallow-code/apispec | add handling for lack of Dict values metadata |
393,976 | 05.05.2018 14:25:44 | -7,200 | dce7c80798191c915d434e3801669eb21c03f8fa | Add test for Dict field values handling | [
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_marshmallow.py",
"new_path": "tests/test_ext_marshmallow.py",
"diff": "@@ -8,7 +8,7 @@ from apispec import APISpec\nfrom apispec.ext.marshmallow import swagger\nfrom .schemas import PetSchema, AnalysisSchema, SampleSchema, RunSchema, \\\nSelfReferencingSchema, OrderedSchema, PatternedObjectSchema, \\\n- DefaultCallableSchema, AnalysisWithListSchema\n+ DefaultCallableSchema, AnalysisWithListSchema, AnalysisWithDictSchema\ndescription = 'This is a sample Petstore server. You can find out more '\n@@ -584,3 +584,12 @@ class TestDefaultCanBeCallable:\nspec.definition('DefaultCallableSchema', schema=DefaultCallableSchema)\nresult = spec._definitions['DefaultCallableSchema']['properties']['numbers']\nassert result['default'] == []\n+\n+\n+class TestDictValues:\n+ def test_dict_values_resolve_to_additional_properties(self, spec):\n+ spec.definition('SampleSchema', schema=SampleSchema)\n+ spec.definition('AnalysisWithDictSchema', schema=AnalysisWithDictSchema)\n+ dict_schema_definition = spec._definitions['AnalysisWithDictSchema']\n+ additional_props = dict_schema_definition['properties']['samplesDict']['additionalProperties']\n+ assert additional_props['$ref'] == '#/definitions/SampleSchema'\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Add test for Dict field values handling |
393,976 | 05.05.2018 14:26:42 | -7,200 | cd300ebffd8974b5c9fe98e8368f26dc029ae41b | Add schema with Dict field | [
{
"change_type": "MODIFY",
"old_path": "tests/schemas.py",
"new_path": "tests/schemas.py",
"diff": "@@ -24,6 +24,10 @@ class AnalysisWithListSchema(Schema):\nsamples = fields.List(fields.Nested(SampleSchema))\n+class AnalysisWithDictSchema(Schema):\n+ samplesDict = fields.Dict(values=fields.Nested(SampleSchema))\n+\n+\nclass PatternedObjectSchema(Schema):\ncount = fields.Int(dump_only=True, **{'x-count': 1})\ncount2 = fields.Int(dump_only=True, x_count2=2)\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Add schema with Dict field |
393,976 | 06.05.2018 20:55:02 | -7,200 | 76cb6a27eff8112b403e6e133fcabddc9a30890e | Use value_container property instead of metadata | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/swagger.py",
"new_path": "apispec/ext/marshmallow/swagger.py",
"diff": "@@ -380,8 +380,8 @@ def field2property(field, spec=None, use_refs=True, dump=True, name=None):\nelif isinstance(field, marshmallow.fields.List):\nret['items'] = field2property(field.container, spec=spec, use_refs=use_refs, dump=dump)\nelif isinstance(field, marshmallow.fields.Dict):\n- if 'values' in field.metadata:\n- ret['additionalProperties'] = field2property(field.metadata['values'], spec=spec, use_refs=use_refs, dump=dump)\n+ if MARSHMALLOW_VERSION_INFO[0] >= 3:\n+ ret['additionalProperties'] = field2property(field.value_container, spec=spec, use_refs=use_refs, dump=dump)\n# Dasherize metadata that starts with x_\nmetadata = {\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Use value_container property instead of metadata |
393,976 | 06.05.2018 20:56:48 | -7,200 | 3af0d2e7d94c6db53a751892ec8422fe465d3de7 | Limit Dict values test to marshmallow < 3 | [
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_marshmallow.py",
"new_path": "tests/test_ext_marshmallow.py",
"diff": "@@ -585,7 +585,8 @@ class TestDefaultCanBeCallable:\nresult = spec._definitions['DefaultCallableSchema']['properties']['numbers']\nassert result['default'] == []\n-\[email protected](swagger.MARSHMALLOW_VERSION_INFO[0] < 3,\n+ reason='Values ignored in marshmallow 2')\nclass TestDictValues:\ndef test_dict_values_resolve_to_additional_properties(self, spec):\nspec.definition('SampleSchema', schema=SampleSchema)\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Limit Dict values test to marshmallow < 3 |
393,976 | 07.05.2018 02:00:39 | -7,200 | 3584c057c27327326a4b87ee5438893d3e656963 | Make Dict values test narrower | [
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_marshmallow.py",
"new_path": "tests/test_ext_marshmallow.py",
"diff": "import pytest\nimport json\n-from marshmallow.fields import Field, DateTime\n+from marshmallow.fields import Field, DateTime, Dict, String\n+from marshmallow import Schema\nfrom apispec import APISpec\nfrom apispec.ext.marshmallow import swagger\nfrom .schemas import PetSchema, AnalysisSchema, SampleSchema, RunSchema, \\\nSelfReferencingSchema, OrderedSchema, PatternedObjectSchema, \\\n- DefaultCallableSchema, AnalysisWithListSchema, AnalysisWithDictSchema\n+ DefaultCallableSchema, AnalysisWithListSchema\ndescription = 'This is a sample Petstore server. You can find out more '\n@@ -585,12 +586,16 @@ class TestDefaultCanBeCallable:\nresult = spec._definitions['DefaultCallableSchema']['properties']['numbers']\nassert result['default'] == []\n+\[email protected](swagger.MARSHMALLOW_VERSION_INFO[0] < 3,\nreason='Values ignored in marshmallow 2')\nclass TestDictValues:\ndef test_dict_values_resolve_to_additional_properties(self, spec):\n- spec.definition('SampleSchema', schema=SampleSchema)\n- spec.definition('AnalysisWithDictSchema', schema=AnalysisWithDictSchema)\n- dict_schema_definition = spec._definitions['AnalysisWithDictSchema']\n- additional_props = dict_schema_definition['properties']['samplesDict']['additionalProperties']\n- assert additional_props['$ref'] == '#/definitions/SampleSchema'\n+\n+ class SchemaWithDict(Schema):\n+ dict_field = Dict(values=String())\n+\n+ spec.definition('SchemaWithDict', schema=SchemaWithDict)\n+ result = spec._definitions['SchemaWithDict']['properties']['dict_field']\n+ assert 'additionalProperties' in result\n+ assert result['additionalProperties'] == 'string'\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Make Dict values test narrower |
393,976 | 07.05.2018 02:01:27 | -7,200 | b4698e47e5fa2ef47c5c940a40c0c1e1805ec0dc | Remove Dict schema | [
{
"change_type": "MODIFY",
"old_path": "tests/schemas.py",
"new_path": "tests/schemas.py",
"diff": "@@ -24,10 +24,6 @@ class AnalysisWithListSchema(Schema):\nsamples = fields.List(fields.Nested(SampleSchema))\n-class AnalysisWithDictSchema(Schema):\n- samplesDict = fields.Dict(values=fields.Nested(SampleSchema))\n-\n-\nclass PatternedObjectSchema(Schema):\ncount = fields.Int(dump_only=True, **{'x-count': 1})\ncount2 = fields.Int(dump_only=True, x_count2=2)\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Remove Dict schema |
393,976 | 07.05.2018 02:16:08 | -7,200 | 4f8c13deb9ae03a36492deda82a983717c868f98 | Access 'type' property of 'additionalProperties' | [
{
"change_type": "MODIFY",
"old_path": "tests/test_ext_marshmallow.py",
"new_path": "tests/test_ext_marshmallow.py",
"diff": "@@ -598,4 +598,4 @@ class TestDictValues:\nspec.definition('SchemaWithDict', schema=SchemaWithDict)\nresult = spec._definitions['SchemaWithDict']['properties']['dict_field']\nassert 'additionalProperties' in result\n- assert result['additionalProperties'] == 'string'\n+ assert result['additionalProperties']['type'] == 'string'\n"
}
]
| Python | MIT License | marshmallow-code/apispec | Access 'type' property of 'additionalProperties' |
393,976 | 07.05.2018 11:18:59 | -7,200 | 9e141f9ea695a38995c936f3a469271743ff0d8e | add check for Dict(values=None) | [
{
"change_type": "MODIFY",
"old_path": "apispec/ext/marshmallow/swagger.py",
"new_path": "apispec/ext/marshmallow/swagger.py",
"diff": "@@ -381,6 +381,7 @@ def field2property(field, spec=None, use_refs=True, dump=True, name=None):\nret['items'] = field2property(field.container, spec=spec, use_refs=use_refs, dump=dump)\nelif isinstance(field, marshmallow.fields.Dict):\nif MARSHMALLOW_VERSION_INFO[0] >= 3:\n+ if field.value_container:\nret['additionalProperties'] = field2property(field.value_container, spec=spec, use_refs=use_refs, dump=dump)\n# Dasherize metadata that starts with x_\n"
}
]
| Python | MIT License | marshmallow-code/apispec | add check for Dict(values=None) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.