Datasets:
base_commit stringlengths 40 40 | created_at stringdate 2014-11-10 05:17:52 2025-10-31 18:00:44 | image_name stringlengths 41 98 | instance_id stringlengths 11 68 | interface stringlengths 33 16.8k ⌀ | language stringclasses 20
values | license stringclasses 16
values | patch stringlengths 198 252k | pr_description stringlengths 0 37.8k | problem_statement stringlengths 0 235k | repo stringlengths 5 63 | test_patch stringlengths 149 150k | FAIL_TO_PASS listlengths 1 118k | PASS_TO_PASS listlengths 0 327k | install_config dict | meta dict |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f52f0bf3d18ca418d1eec4afd1370751fdd914ce | 2021-06-22 22:21:33 | docker.io/swerebenchv2/elastic-synthetics:316-f52f0bf | elastic__synthetics-316 | No new interfaces are introduced. | ts | MIT | diff --git a/src/core/runner.ts b/src/core/runner.ts
index 2872cf5..649a22a 100644
--- a/src/core/runner.ts
+++ b/src/core/runner.ts
@@ -131,6 +131,7 @@ export default class Runner extends EventEmitter {
journeys: Journey[] = [];
hooks: SuiteHooks = { beforeAll: [], afterAll: [] };
screenshotPath = join(CACHE_PATH, 'screenshots');
+ hookError: Error | undefined;
static async createContext(options: RunOptions): Promise<JourneyContext> {
const start = monotonicTimeInSeconds();
@@ -291,13 +292,12 @@ export default class Runner extends EventEmitter {
result: JourneyContext & JourneyResult,
options: RunOptions
) {
- const { pluginManager, start, params, status, error } = result;
+ const { pluginManager, start, status, error } = result;
const pluginOutput = await pluginManager.output();
this.emit('journey:end', {
journey,
status,
error,
- params,
start,
end: monotonicTimeInSeconds(),
options,
@@ -313,6 +313,33 @@ export default class Runner extends EventEmitter {
}
}
+ /**
+ * Simulate a journey run to capture errors in the beforeAll hook
+ */
+ async runFakeJourney(journey: Journey, options: RunOptions) {
+ const start = monotonicTimeInSeconds();
+ this.emit('journey:start', {
+ journey,
+ timestamp: getTimestamp(),
+ params: options.params,
+ });
+ const result: JourneyResult = {
+ status: 'failed',
+ error: this.hookError,
+ };
+ this.emit('journey:end', {
+ journey,
+ start,
+ options,
+ end: monotonicTimeInSeconds(),
+ ...result,
+ });
+ if (options.reporter === 'json') {
+ await once(this, 'journey:end:reported');
+ }
+ return result;
+ }
+
async runJourney(journey: Journey, options: RunOptions) {
const result: JourneyResult = {
status: 'succeeded',
@@ -376,7 +403,8 @@ export default class Runner extends EventEmitter {
await this.runBeforeAllHook({
env: options.environment,
params: options.params,
- });
+ }).catch(e => (this.hookError = e));
+
const { dryRun, match, tags } = options;
for (const journey of this.journeys) {
/**
@@ -389,7 +417,9 @@ export default class Runner extends EventEmitter {
if (!journey.isMatch(match, tags)) {
continue;
}
- const journeyResult = await this.runJourney(journey, options);
+ const journeyResult: JourneyResult = this.hookError
+ ? await this.runFakeJourney(journey, options)
+ : await this.runJourney(journey, options);
result[journey.name] = journeyResult;
}
await Gatherer.stop();
diff --git a/src/reporters/json.ts b/src/reporters/json.ts
index f169df5..08d13bc 100644
--- a/src/reporters/json.ts
+++ b/src/reporters/json.ts
@@ -332,7 +332,6 @@ export async function gatherScreenshots(
screenshotsPath: string,
callback: (step: Step, data: string) => Promise<void>
) {
- const screenshots: Array<ScreenshotOutput> = [];
if (isDirectory(screenshotsPath)) {
await totalist(screenshotsPath, async (_, absPath) => {
try {
@@ -344,7 +343,6 @@ export async function gatherScreenshots(
}
});
}
- return screenshots;
}
export default class JSONReporter extends BaseReporter {
@@ -425,6 +423,9 @@ export default class JSONReporter extends BaseReporter {
await gatherScreenshots(
join(CACHE_PATH, 'screenshots'),
async (step, data) => {
+ if (!data) {
+ return;
+ }
if (ssblocks) {
await this.writeScreenshotBlocks(journey, step, data);
} else {
| fix: capture beforeAll hook errors
+ fix #280
+ We capture the beforeAll hook errors and any error that happens in any one of the hooks would be captured and all journeys that run on the current invocation will report that error event with `failed` status to be able to captured as part of the Uptime UI.
+ `afterAll` errors behaves the same - we report them in the stderror logs which will be captured by Heartbeat. | propagate errors from `beforeAll` and `afterAll` hooks
+ Now error in the `beforeAll` and `afterAll` hooks would be captured and reported as error, but they will not be associated with the reporters in the correct way.
+ Without associating these errors, the Uptime UI will have no information about what happened during the context of a single execution.
We have to figure out a way to solve this problem. | elastic/synthetics | diff --git a/__tests__/core/runner.test.ts b/__tests__/core/runner.test.ts
index a60b6ed..d4ba7d9 100644
--- a/__tests__/core/runner.test.ts
+++ b/__tests__/core/runner.test.ts
@@ -147,6 +147,23 @@ describe('runner', () => {
});
});
+ it('run journey - failed on beforeAll', async () => {
+ const error = new Error('Broken beforeAll hook');
+ runner.addHook('beforeAll', () => {
+ throw error;
+ });
+ runner.addJourney(new Journey({ name: 'j1' }, () => step('step1', noop)));
+ runner.addJourney(new Journey({ name: 'j2' }, () => step('step1', noop)));
+ const result = await runner.run({
+ wsEndpoint,
+ outfd: fs.openSync(dest, 'w'),
+ });
+ expect(result).toEqual({
+ j1: { status: 'failed', error },
+ j2: { status: 'failed', error },
+ });
+ });
+
it('run step', async () => {
const j1 = journey('j1', async ({ page }) => {
step('step1', async () => {
| [
"run journey - failed on beforeAll"
] | [
"log to specified fd",
"computes trace of the tab",
"compute user timing metrics",
"compute user experience trace and metrics",
"computes layout shift",
"computes cls with session window",
"calculate cls score with simulated sessions",
"cls to 0 when no events found",
"computes filmstrips",
"add s... | {
"base_image_name": "node_20",
"docker_specs": null,
"install": [
"npm ci --quiet"
],
"log_parser": "parse_log_js_4",
"test_cmd": "npm run test:unit -- --verbose --no-color"
} | {
"llm_metadata": {
"code": "A",
"confidence": 0.97,
"detected_issues": {
"B1": false,
"B2": false,
"B3": false,
"B4": false,
"B5": false,
"B6": false
},
"difficulty": "medium",
"external_urls": [],
"intent_completeness": "complete",
"pr_categories": [
"minor_bug"
],
"reasoning": "The issue requests that errors thrown in beforeAll/afterAll hooks be captured and cause all journeys to fail with the same error. The test adds a beforeAll hook that throws and expects each journey's result to be {status:'failed', error} with the same Error object. The test aligns with the described requirement and does not introduce unrelated expectations. No signals of B‑categories (no external URLs, naming constraints, ambiguous spec, etc.) are present, so the task is clearly solvable.",
"test_alignment_issues": []
},
"num_modified_files": 2,
"num_modified_lines": 37,
"pr_author": "vigneshshanmugam",
"pr_labels": [],
"pr_url": null
} |
848d28d67e45cda7a06c4c8ed2768e6a8cb1c016 | 2020-05-31 15:27:12 | docker.io/swerebenchv2/wtforms-wtforms:614-848d28d | wtforms__wtforms-614 | Method: Flags.__getattr__(self, name)
Location: wtforms/fields/core.py → class Flags
Inputs: *name* – attribute name requested on a Flags instance.
Outputs: Returns the attribute’s value if it exists; otherwise returns **None** (previously returned False).
Description: Provides a unified flags object where missing flags evaluate to None, enabling flag‑based widget rendering.
Method: Input.__call__(self, field, **kwargs)
Location: wtforms/widgets/core.py → class Input
Inputs: *field* – a WTForms Field instance; **kwargs – optional HTML attributes passed at render time.
Outputs: A Markup string for an `<input …>` element; automatically injects any flag attributes whose names appear in the widget’s *validation_attrs* list and are set on *field.flags*.
Description: Renders HTML5‑compatible input elements, pulling validation‑related attributes (e.g., required, minlength, maxlength, min, max, step) from the field’s flags.
Method: TextInput.__call__(self, field, **kwargs) *(inherited, uses Input.__call__)*
Location: wtforms/widgets/core.py → class TextInput
Inputs: Same as Input.__call__.
Outputs: `<input type="text" …>` markup with added validation attributes.
Description: Text input widget that now supports required, maxlength, minlength, and pattern attributes derived from field flags.
Method: PasswordInput.__call__(self, field, **kwargs)
Location: wtforms/widgets/core.py → class PasswordInput
Inputs: Same as Input.__call__.
Outputs: `<input type="password" …>` markup with validation attributes.
Description: Password input widget supporting the same validation flags as TextInput.
Method: TextArea.__call__(self, field, **kwargs)
Location: wtforms/widgets/core.py → class TextArea
Inputs: *field*; **kwargs.
Outputs: `<textarea …>` markup with required, maxlength, minlength attributes taken from flags.
Description: Textarea widget now propagates flag‑based validation attributes.
Method: Select.__call__(self, field, **kwargs)
Location: wtforms/widgets/core.py → class Select
Inputs: *field*; **kwargs.
Outputs: `<select …>` markup with required attribute from flags.
Description: Select widget now adds a required attribute when the field’s flags indicate it.
Method: SearchField.__init__(self, label=None, validators=None, **kwargs)
Location: wtforms/fields/core.py → class SearchField (inherits StringField)
Inputs: *label*, *validators*, additional field kwargs.
Outputs: Instance of a field rendering `<input type="search">`.
Description: New convenience field for HTML `search` input type, using the SearchInput widget.
Method: TelField.__init__(self, label=None, validators=None, **kwargs)
Location: wtforms/fields/core.py → class TelField (inherits StringField)
Inputs: Same as SearchField.
Outputs: Instance rendering `<input type="tel">`.
Description: New field for telephone inputs.
Method: URLField.__init__(self, label=None, validators=None, **kwargs)
Location: wtforms/fields/core.py → class URLField (inherits StringField)
Inputs: Same as SearchField.
Outputs: Instance rendering `<input type="url">`.
Description: New field for URL inputs.
Method: EmailField.__init__(self, label=None, validators=None, **kwargs)
Location: wtforms/fields/core.py → class EmailField (inherits StringField)
Inputs: Same as SearchField.
Outputs: Instance rendering `<input type="email">`.
Description: New field for email inputs.
Method: DateTimeLocalField.__init__(self, label=None, validators=None, format="%Y-%m-%d %H:%M:%S", **kwargs)
Location: wtforms/fields/core.py → class DateTimeLocalField (inherits DateTimeField)
Inputs: *label*, *validators*, *format*, additional kwargs.
Outputs: Instance rendering `<input type="datetime-local">`.
Description: New field for HTML5 datetime‑local inputs.
Method: IntegerRangeField.__init__(self, label=None, validators=None, **kwargs)
Location: wtforms/fields/core.py → class IntegerRangeField (inherits IntegerField)
Inputs: Same as IntegerField.
Outputs: Instance rendering `<input type="range">`.
Description: New field for numeric range inputs, using the RangeInput widget.
Method: DecimalRangeField.__init__(self, label=None, validators=None, **kwargs)
Location: wtforms/fields/core.py → class DecimalRangeField (inherits DecimalField)
Inputs: Same as DecimalField.
Outputs: Instance rendering `<input type="range">` with step="any".
Description: New field for decimal range inputs.
Method: Length.__init__(self, min=-1, max=-1, message=None)
Location: wtforms/validators.py → class Length
Inputs: *min* (int, default –1), *max* (int, default –1), *message* (optional).
Outputs: Validator instance with *field_flags* dict containing “minlength” and/or “maxlength” when limits are set.
Description: Length validator now provides flag information for widget rendering.
Method: NumberRange.__init__(self, min=None, max=None, message=None)
Location: wtforms/validators.py → class NumberRange
Inputs: *min* (numeric or None), *max* (numeric or None), *message*.
Outputs: Validator instance with *field_flags* dict containing “min” and/or “max”.
Description: NumberRange validator now supplies min/max flags for HTML5 widgets.
Method: Optional.__init__(self, strip_whitespace=True)
Location: wtforms/validators.py → class Optional
Inputs: *strip_whitespace* (bool).
Outputs: Validator instance with *field_flags* = {"optional": True}.
Description: Optional validator now sets an explicit “optional” flag for widgets.
Method: DataRequired.__init__(self, message=None)
Location: wtforms/validators.py → class DataRequired
Inputs: *message* (optional).
Outputs: Validator instance with *field_flags* = {"required": True}.
Description: DataRequired now provides a required flag for widget rendering.
Method: InputRequired.__init__(self, message=None)
Location: wtforms/validators.py → class InputRequired
Inputs: *message* (optional).
Outputs: Validator instance with *field_flags* = {"required": True}.
Description: InputRequired now provides the required flag similarly to DataRequired.
Function: html_params(**kwargs) *(unchanged signature, but now used by widgets to include flag attributes)*
Location: wtforms/widgets/core.py → helper function.
Inputs: Arbitrary HTML attribute key/value pairs.
Outputs: Properly escaped attribute string.
Description: Generates the attribute list for widget rendering, now receives additional validation attributes from flags.
| python | BSD-3-Clause | diff --git a/CHANGES.rst b/CHANGES.rst
index 50f43a2..a199f46 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -34,7 +34,7 @@ Unreleased
- Render attribute names like ``for_`` and ``class_`` are normalized
consistently so later values override those specified earlier.
:issue:`449`, :pr:`596`
-
+- Flags can take non-boolean values. :issue:`406` :pr:`467`
Version 2.3.1
-------------
diff --git a/docs/fields.rst b/docs/fields.rst
index ed047ce..0bd3e32 100644
--- a/docs/fields.rst
+++ b/docs/fields.rst
@@ -182,10 +182,10 @@ The Field base class
.. attribute:: flags
- An object containing boolean flags set either by the field itself, or
+ An object containing flags set either by the field itself, or
by validators on the field. For example, the built-in
:class:`~wtforms.validators.InputRequired` validator sets the `required` flag.
- An unset flag will result in :const:`False`.
+ An unset flag will result in :const:`None`.
.. code-block:: html+django
@@ -220,10 +220,14 @@ refer to a single input from the form.
.. autoclass:: DateTimeField(default field arguments, format='%Y-%m-%d %H:%M:%S')
- For better date/time fields, see the :mod:`dateutil extension <wtforms.ext.dateutil.fields>`
+.. autoclass:: DateTimeLocalField(default field arguments, format='%Y-%m-%d %H:%M:%S')
.. autoclass:: DecimalField(default field arguments, places=2, rounding=None, use_locale=False, number_format=None)
+.. autoclass:: DecimalRangeField(default field arguments)
+
+.. autoclass:: EmailField(default field arguments)
+
.. autoclass:: FileField(default field arguments)
Example usage::
@@ -252,6 +256,8 @@ refer to a single input from the form.
.. autoclass:: IntegerField(default field arguments)
+.. autoclass:: IntegerRangeField(default field arguments)
+
.. autoclass:: RadioField(default field arguments, choices=[], coerce=str)
.. code-block:: jinja
@@ -323,6 +329,8 @@ refer to a single input from the form.
a list of fields each representing an option. The rendering of this can be
further controlled by specifying `option_widget=`.
+.. autoclass:: SearchField(default field arguments)
+
.. autoclass:: SelectMultipleField(default field arguments, choices=[], coerce=str, option_widget=None)
The data on the SelectMultipleField is stored as a list of objects, each of
@@ -338,6 +346,13 @@ refer to a single input from the form.
{{ form.username(size=30, maxlength=50) }}
+.. autoclass:: TelField(default field arguments)
+
+.. autoclass:: TimeField(default field arguments, format='%H:%M')
+
+.. autoclass:: URLField(default field arguments)
+
+
Convenience Fields
------------------
@@ -559,40 +574,3 @@ Additional Helper Classes
.. attribute:: text
The original label text passed to the field's constructor.
-
-HTML5 Fields
-------------
-
-In addition to basic HTML fields, WTForms also supplies fields for the HTML5
-standard. These fields can be accessed under the :mod:`wtforms.fields.html5` namespace.
-In reality, these fields are just convenience fields that extend basic fields
-and implement HTML5 specific widgets. These widgets are located in the :mod:`wtforms.widgets.html5`
-namespace and can be overridden or modified just like any other widget.
-
-.. module:: wtforms.fields.html5
-
-.. autoclass:: SearchField(default field arguments)
-
-.. autoclass:: TelField(default field arguments)
-
-.. autoclass:: URLField(default field arguments)
-
-.. autoclass:: EmailField(default field arguments)
-
-.. autoclass:: DateTimeField(default field arguments, format='%Y-%m-%d %H:%M:%S')
-
-.. autoclass:: DateField(default field arguments, format='%Y-%m-%d')
-
-.. autoclass:: MonthField(default field arguments, format='%Y-%m')
-
-.. autoclass:: TimeField(default field arguments, format='%H:%M')
-
-.. autoclass:: DateTimeLocalField(default field arguments, format='%Y-%m-%d %H:%M:%S')
-
-.. autoclass:: IntegerField(default field arguments)
-
-.. autoclass:: DecimalField(default field arguments)
-
-.. autoclass:: IntegerRangeField(default field arguments)
-
-.. autoclass:: DecimalRangeField(default field arguments)
diff --git a/docs/validators.rst b/docs/validators.rst
index cdb9627..818c018 100644
--- a/docs/validators.rst
+++ b/docs/validators.rst
@@ -177,22 +177,21 @@ which will then be available on the :attr:`field's flags object
To specify flags on your validator, set the ``field_flags`` attribute on your
validator. When the Field is constructed, the flags with the same name will be
-set to True on your field. For example, let's imagine a validator that
+set on your field. For example, let's imagine a validator that
validates that input is valid BBCode. We can set a flag on the field then to
signify that the field accepts BBCode::
# class implementation
class ValidBBCode(object):
- field_flags = ('accepts_bbcode', )
-
- pass # validator implementation here
+ def __init__(self):
+ self.field_flags = {'accepts_bbcode': True}
# factory implementation
def valid_bbcode():
def _valid_bbcode(form, field):
pass # validator implementation here
- _valid_bbcode.field_flags = ('accepts_bbcode', )
+ _valid_bbcode.field_flags = {'accepts_bbcode': True}
return _valid_bbcode
Then we can check it in our template, so we can then place a note to the user:
@@ -206,7 +205,10 @@ Then we can check it in our template, so we can then place a note to the user:
Some considerations on using flags:
-* Flags can only set boolean values, and another validator cannot unset them.
-* If multiple fields set the same flag, its value is still True.
+* Boolean flags will set HTML valueless attributes (e.g. `{required: True}`
+ will give `<input type="text" required>`). Other flag types will set regular
+ HTML attributes (e.g. `{maxlength: 8}` will give `<input type="text" maxlength="8">`).
+* If multiple validators set the same flag, the flag will have the value set
+ by the first validator.
* Flags are set from validators only in :meth:`Field.__init__`, so inline
validators and extra passed-in validators cannot set them.
diff --git a/docs/widgets.rst b/docs/widgets.rst
index 81b96c0..5c4f009 100644
--- a/docs/widgets.rst
+++ b/docs/widgets.rst
@@ -14,36 +14,30 @@ recognize as not needing to be auto-escaped.
Built-in widgets
----------------
-.. autoclass:: wtforms.widgets.ListWidget
-.. autoclass:: wtforms.widgets.TableWidget
+.. autoclass:: wtforms.widgets.ColorInput
+.. autoclass:: wtforms.widgets.CheckboxInput
+.. autoclass:: wtforms.widgets.DateTimeInput
+.. autoclass:: wtforms.widgets.DateTimeLocalInput
+.. autoclass:: wtforms.widgets.DateInput
+.. autoclass:: wtforms.widgets.EmailInput
+.. autoclass:: wtforms.widgets.FileInput
+.. autoclass:: wtforms.widgets.HiddenInput
.. autoclass:: wtforms.widgets.Input
-.. autoclass:: wtforms.widgets.TextInput()
+.. autoclass:: wtforms.widgets.ListWidget
+.. autoclass:: wtforms.widgets.MonthInput
+.. autoclass:: wtforms.widgets.NumberInput
.. autoclass:: wtforms.widgets.PasswordInput
-.. autoclass:: wtforms.widgets.HiddenInput()
-.. autoclass:: wtforms.widgets.CheckboxInput()
-.. autoclass:: wtforms.widgets.FileInput()
-.. autoclass:: wtforms.widgets.SubmitInput()
-.. autoclass:: wtforms.widgets.TextArea
+.. autoclass:: wtforms.widgets.RangeInput
+.. autoclass:: wtforms.widgets.SubmitInput
+.. autoclass:: wtforms.widgets.SearchInput
.. autoclass:: wtforms.widgets.Select
-
-HTML5 widgets
--------------
-
-.. module:: wtforms.widgets.html5
-
-.. autoclass:: wtforms.widgets.html5.ColorInput
-.. autoclass:: wtforms.widgets.html5.DateTimeInput
-.. autoclass:: wtforms.widgets.html5.DateTimeLocalInput
-.. autoclass:: wtforms.widgets.html5.DateInput
-.. autoclass:: wtforms.widgets.html5.EmailInput
-.. autoclass:: wtforms.widgets.html5.MonthInput
-.. autoclass:: wtforms.widgets.html5.NumberInput
-.. autoclass:: wtforms.widgets.html5.RangeInput
-.. autoclass:: wtforms.widgets.html5.SearchInput
-.. autoclass:: wtforms.widgets.html5.TelInput
-.. autoclass:: wtforms.widgets.html5.TimeInput
-.. autoclass:: wtforms.widgets.html5.URLInput
-.. autoclass:: wtforms.widgets.html5.WeekInput
+.. autoclass:: wtforms.widgets.TableWidget
+.. autoclass:: wtforms.widgets.TelInput
+.. autoclass:: wtforms.widgets.TextArea
+.. autoclass:: wtforms.widgets.TextInput
+.. autoclass:: wtforms.widgets.TimeInput
+.. autoclass:: wtforms.widgets.URLInput
+.. autoclass:: wtforms.widgets.WeekInput
Widget-Building Utilities
-------------------------
diff --git a/src/wtforms/fields/__init__.py b/src/wtforms/fields/__init__.py
index 1f770d3..e429631 100644
--- a/src/wtforms/fields/__init__.py
+++ b/src/wtforms/fields/__init__.py
@@ -3,6 +3,5 @@ from wtforms.fields.core import Field
from wtforms.fields.core import Flags
from wtforms.fields.core import Label
from wtforms.fields.core import SelectFieldBase
-from wtforms.fields.html5 import *
from wtforms.fields.simple import *
from wtforms.utils import unset_value as _unset_value
diff --git a/src/wtforms/fields/core.py b/src/wtforms/fields/core.py
index d835092..8724356 100644
--- a/src/wtforms/fields/core.py
+++ b/src/wtforms/fields/core.py
@@ -2,6 +2,7 @@ import datetime
import decimal
import inspect
import itertools
+import warnings
from markupsafe import escape
from markupsafe import Markup
@@ -15,18 +16,25 @@ from wtforms.validators import ValidationError
__all__ = (
"BooleanField",
"DecimalField",
+ "DecimalRangeField",
"DateField",
"DateTimeField",
+ "DateTimeLocalField",
+ "EmailField",
"FieldList",
"FloatField",
"FormField",
"IntegerField",
+ "IntegerRangeField",
"RadioField",
+ "SearchField",
"SelectField",
"SelectMultipleField",
"StringField",
+ "TelField",
"TimeField",
"MonthField",
+ "URLField",
)
@@ -143,9 +151,21 @@ class Field:
self.widget = widget
for v in itertools.chain(self.validators, [self.widget]):
- flags = getattr(v, "field_flags", ())
- for f in flags:
- setattr(self.flags, f, True)
+ flags = getattr(v, "field_flags", {})
+
+ # check for legacy format, remove eventually
+ if isinstance(flags, tuple):
+ warnings.warn(
+ "Flags should be stored in dicts and not in tuples. "
+ "The next version of WTForms will abandon support "
+ "for flags in tuples.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ flags = {flag_name: True for flag_name in flags}
+
+ for k, v in flags.items():
+ setattr(self.flags, k, v)
def __str__(self):
"""
@@ -408,15 +428,15 @@ class UnboundField:
class Flags:
"""
- Holds a set of boolean flags as attributes.
+ Holds a set of flags as attributes.
- Accessing a non-existing attribute returns False for its value.
+ Accessing a non-existing attribute returns None for its value.
"""
def __getattr__(self, name):
if name.startswith("_"):
return super().__getattr__(name)
- return False
+ return None
def __contains__(self, name):
return getattr(self, name)
@@ -670,7 +690,7 @@ class IntegerField(Field):
is ignored and will not be accepted as a value.
"""
- widget = widgets.TextInput()
+ widget = widgets.NumberInput()
def __init__(self, label=None, validators=None, **kwargs):
super().__init__(label, validators, **kwargs)
@@ -721,7 +741,7 @@ class DecimalField(LocaleAwareNumberField):
format for the locale.
"""
- widget = widgets.TextInput()
+ widget = widgets.NumberInput(step="any")
def __init__(
self, label=None, validators=None, places=unset_value, rounding=None, **kwargs
@@ -842,7 +862,7 @@ class DateTimeField(Field):
A text field which stores a `datetime.datetime` matching a format.
"""
- widget = widgets.TextInput()
+ widget = widgets.DateTimeInput()
def __init__(
self, label=None, validators=None, format="%Y-%m-%d %H:%M:%S", **kwargs
@@ -871,6 +891,8 @@ class DateField(DateTimeField):
Same as DateTimeField, except stores a `datetime.date`.
"""
+ widget = widgets.DateInput()
+
def __init__(self, label=None, validators=None, format="%Y-%m-%d", **kwargs):
super().__init__(label, validators, format, **kwargs)
@@ -889,6 +911,8 @@ class TimeField(DateTimeField):
Same as DateTimeField, except stores a `time`.
"""
+ widget = widgets.TimeInput()
+
def __init__(self, label=None, validators=None, format="%H:%M", **kwargs):
super().__init__(label, validators, format, **kwargs)
@@ -908,6 +932,8 @@ class MonthField(DateField):
with `day = 1`.
"""
+ widget = widgets.MonthInput()
+
def __init__(self, label=None, validators=None, format="%Y-%m", **kwargs):
super().__init__(label, validators, format, **kwargs)
@@ -1189,3 +1215,59 @@ class FieldList(Field):
@property
def data(self):
return [f.data for f in self.entries]
+
+
+class SearchField(StringField):
+ """
+ Represents an ``<input type="search">``.
+ """
+
+ widget = widgets.SearchInput()
+
+
+class TelField(StringField):
+ """
+ Represents an ``<input type="tel">``.
+ """
+
+ widget = widgets.TelInput()
+
+
+class URLField(StringField):
+ """
+ Represents an ``<input type="url">``.
+ """
+
+ widget = widgets.URLInput()
+
+
+class EmailField(StringField):
+ """
+ Represents an ``<input type="email">``.
+ """
+
+ widget = widgets.EmailInput()
+
+
+class DateTimeLocalField(DateTimeField):
+ """
+ Represents an ``<input type="datetime-local">``.
+ """
+
+ widget = widgets.DateTimeLocalInput()
+
+
+class IntegerRangeField(IntegerField):
+ """
+ Represents an ``<input type="range">``.
+ """
+
+ widget = widgets.RangeInput()
+
+
+class DecimalRangeField(DecimalField):
+ """
+ Represents an ``<input type="range">``.
+ """
+
+ widget = widgets.RangeInput(step="any")
diff --git a/src/wtforms/fields/html5.py b/src/wtforms/fields/html5.py
deleted file mode 100644
index 26d7efa..0000000
--- a/src/wtforms/fields/html5.py
+++ /dev/null
@@ -1,121 +0,0 @@
-from . import core
-from ..widgets import html5 as widgets
-
-__all__ = (
- "DateField",
- "DateTimeField",
- "DateTimeLocalField",
- "DecimalField",
- "DecimalRangeField",
- "EmailField",
- "IntegerField",
- "IntegerRangeField",
- "SearchField",
- "TelField",
- "TimeField",
- "URLField",
-)
-
-
-class SearchField(core.StringField):
- """
- Represents an ``<input type="search">``.
- """
-
- widget = widgets.SearchInput()
-
-
-class TelField(core.StringField):
- """
- Represents an ``<input type="tel">``.
- """
-
- widget = widgets.TelInput()
-
-
-class URLField(core.StringField):
- """
- Represents an ``<input type="url">``.
- """
-
- widget = widgets.URLInput()
-
-
-class EmailField(core.StringField):
- """
- Represents an ``<input type="email">``.
- """
-
- widget = widgets.EmailInput()
-
-
-class DateTimeField(core.DateTimeField):
- """
- Represents an ``<input type="datetime">``.
- """
-
- widget = widgets.DateTimeInput()
-
-
-class DateField(core.DateField):
- """
- Represents an ``<input type="date">``.
- """
-
- widget = widgets.DateInput()
-
-
-class TimeField(core.TimeField):
- """
- Represents an ``<input type="time">``.
- """
-
- widget = widgets.TimeInput()
-
-
-class MonthField(core.MonthField):
- """
- Represents an ``<input type="month">``.
- """
-
- widget = widgets.MonthInput()
-
-
-class DateTimeLocalField(core.DateTimeField):
- """
- Represents an ``<input type="datetime-local">``.
- """
-
- widget = widgets.DateTimeLocalInput()
-
-
-class IntegerField(core.IntegerField):
- """
- Represents an ``<input type="number">``.
- """
-
- widget = widgets.NumberInput()
-
-
-class DecimalField(core.DecimalField):
- """
- Represents an ``<input type="number">``.
- """
-
- widget = widgets.NumberInput(step="any")
-
-
-class IntegerRangeField(core.IntegerField):
- """
- Represents an ``<input type="range">``.
- """
-
- widget = widgets.RangeInput()
-
-
-class DecimalRangeField(core.DecimalField):
- """
- Represents an ``<input type="range">``.
- """
-
- widget = widgets.RangeInput(step="any")
diff --git a/src/wtforms/validators.py b/src/wtforms/validators.py
index 2d6bea2..059f32c 100644
--- a/src/wtforms/validators.py
+++ b/src/wtforms/validators.py
@@ -114,6 +114,8 @@ class Length:
Error message to raise in case of a validation error. Can be
interpolated using `%(min)d` and `%(max)d` if desired. Useful defaults
are provided depending on the existence of min and max.
+
+ When supported, sets the `minlength` and `maxlength` attributes on widgets.
"""
def __init__(self, min=-1, max=-1, message=None):
@@ -124,6 +126,11 @@ class Length:
self.min = min
self.max = max
self.message = message
+ self.field_flags = {}
+ if self.min != -1:
+ self.field_flags["minlength"] = self.min
+ if self.max != -1:
+ self.field_flags["maxlength"] = self.max
def __call__(self, form, field):
length = field.data and len(field.data) or 0
@@ -174,12 +181,19 @@ class NumberRange:
Error message to raise in case of a validation error. Can be
interpolated using `%(min)s` and `%(max)s` if desired. Useful defaults
are provided depending on the existence of min and max.
+
+ When supported, sets the `min` and `max` attributes on widgets.
"""
def __init__(self, min=None, max=None, message=None):
self.min = min
self.max = max
self.message = message
+ self.field_flags = {}
+ if self.min is not None:
+ self.field_flags["min"] = self.min
+ if self.max is not None:
+ self.field_flags["max"] = self.max
def __call__(self, form, field):
data = field.data
@@ -215,9 +229,9 @@ class Optional:
:param strip_whitespace:
If True (the default) also stop the validation chain on input which
consists of only whitespace.
- """
- field_flags = ("optional",)
+ Sets the `optional` attribute on widgets.
+ """
def __init__(self, strip_whitespace=True):
if strip_whitespace:
@@ -225,6 +239,8 @@ class Optional:
else:
self.string_check = lambda s: s
+ self.field_flags = {"optional": True}
+
def __call__(self, form, field):
if (
not field.raw_data
@@ -256,12 +272,13 @@ class DataRequired:
:param message:
Error message to raise in case of a validation error.
- """
- field_flags = ("required",)
+ Sets the `required` attribute on widgets.
+ """
def __init__(self, message=None):
self.message = message
+ self.field_flags = {"required": True}
def __call__(self, form, field):
if not field.data or isinstance(field.data, str) and not field.data.strip():
@@ -281,12 +298,13 @@ class InputRequired:
Note there is a distinction between this and DataRequired in that
InputRequired looks that form-input data was provided, and DataRequired
looks at the post-coercion data.
- """
- field_flags = ("required",)
+ Sets the `required` attribute on widgets.
+ """
def __init__(self, message=None):
self.message = message
+ self.field_flags = {"required": True}
def __call__(self, form, field):
if not field.raw_data or not field.raw_data[0]:
diff --git a/src/wtforms/widgets/core.py b/src/wtforms/widgets/core.py
index 3e2a2eb..a0e0e61 100644
--- a/src/wtforms/widgets/core.py
+++ b/src/wtforms/widgets/core.py
@@ -3,17 +3,30 @@ from markupsafe import Markup
__all__ = (
"CheckboxInput",
+ "ColorInput",
+ "DateInput",
+ "DateTimeInput",
+ "DateTimeLocalInput",
+ "EmailInput",
"FileInput",
"HiddenInput",
"ListWidget",
+ "MonthInput",
+ "NumberInput",
+ "Option",
"PasswordInput",
"RadioInput",
+ "RangeInput",
+ "SearchInput",
"Select",
"SubmitInput",
"TableWidget",
"TextArea",
"TextInput",
- "Option",
+ "TelInput",
+ "TimeInput",
+ "URLInput",
+ "WeekInput",
)
@@ -148,6 +161,7 @@ class Input:
"""
html_params = staticmethod(html_params)
+ validation_attrs = ["required"]
def __init__(self, input_type=None):
if input_type is not None:
@@ -158,8 +172,10 @@ class Input:
kwargs.setdefault("type", self.input_type)
if "value" not in kwargs:
kwargs["value"] = field._value()
- if "required" not in kwargs and "required" in getattr(field, "flags", []):
- kwargs["required"] = True
+ flags = getattr(field, "flags", {})
+ for k in dir(flags):
+ if k in self.validation_attrs and k not in kwargs:
+ kwargs[k] = getattr(flags, k)
return Markup("<input %s>" % self.html_params(name=field.name, **kwargs))
@@ -169,6 +185,7 @@ class TextInput(Input):
"""
input_type = "text"
+ validation_attrs = ["required", "maxlength", "minlength", "pattern"]
class PasswordInput(Input):
@@ -181,6 +198,7 @@ class PasswordInput(Input):
"""
input_type = "password"
+ validation_attrs = ["required", "maxlength", "minlength", "pattern"]
def __init__(self, hide_value=True):
self.hide_value = hide_value
@@ -196,9 +214,12 @@ class HiddenInput(Input):
Render a hidden input.
"""
- field_flags = ("hidden",)
input_type = "hidden"
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.field_flags = {"hidden": True}
+
class CheckboxInput(Input):
"""
@@ -238,6 +259,7 @@ class FileInput(Input):
"""
input_type = "file"
+ validation_attrs = ["required", "accept"]
def __init__(self, multiple=False):
super().__init__()
@@ -275,10 +297,14 @@ class TextArea:
`rows` and `cols` ought to be passed as keyword args when rendering.
"""
+ validation_attrs = ["required", "maxlength", "minlength"]
+
def __call__(self, field, **kwargs):
kwargs.setdefault("id", field.id)
- if "required" not in kwargs and "required" in getattr(field, "flags", []):
- kwargs["required"] = True
+ flags = getattr(field, "flags", {})
+ for k in dir(flags):
+ if k in self.validation_attrs and k not in kwargs:
+ kwargs[k] = getattr(flags, k)
return Markup(
"<textarea %s>\r\n%s</textarea>"
% (html_params(name=field.name, **kwargs), escape(field._value()))
@@ -297,6 +323,8 @@ class Select:
`(value, label, selected)`.
"""
+ validation_attrs = ["required"]
+
def __init__(self, multiple=False):
self.multiple = multiple
@@ -304,8 +332,10 @@ class Select:
kwargs.setdefault("id", field.id)
if self.multiple:
kwargs["multiple"] = True
- if "required" not in kwargs and "required" in getattr(field, "flags", []):
- kwargs["required"] = True
+ flags = getattr(field, "flags", {})
+ for k in dir(flags):
+ if k in self.validation_attrs and k not in kwargs:
+ kwargs[k] = getattr(flags, k)
html = ["<select %s>" % html_params(name=field.name, **kwargs)]
for val, label, selected in field.iter_choices():
html.append(self.render_option(val, label, selected))
@@ -338,3 +368,141 @@ class Option:
return Select.render_option(
field._value(), field.label.text, field.checked, **kwargs
)
+
+
+class SearchInput(Input):
+ """
+ Renders an input with type "search".
+ """
+
+ input_type = "search"
+ validation_attrs = ["required", "maxlength", "minlength", "pattern"]
+
+
+class TelInput(Input):
+ """
+ Renders an input with type "tel".
+ """
+
+ input_type = "tel"
+ validation_attrs = ["required", "maxlength", "minlength", "pattern"]
+
+
+class URLInput(Input):
+ """
+ Renders an input with type "url".
+ """
+
+ input_type = "url"
+ validation_attrs = ["required", "maxlength", "minlength", "pattern"]
+
+
+class EmailInput(Input):
+ """
+ Renders an input with type "email".
+ """
+
+ input_type = "email"
+ validation_attrs = ["required", "maxlength", "minlength", "pattern"]
+
+
+class DateTimeInput(Input):
+ """
+ Renders an input with type "datetime".
+ """
+
+ input_type = "datetime"
+ validation_attrs = ["required", "max", "min", "step"]
+
+
+class DateInput(Input):
+ """
+ Renders an input with type "date".
+ """
+
+ input_type = "date"
+ validation_attrs = ["required", "max", "min", "step"]
+
+
+class MonthInput(Input):
+ """
+ Renders an input with type "month".
+ """
+
+ input_type = "month"
+ validation_attrs = ["required", "max", "min", "step"]
+
+
+class WeekInput(Input):
+ """
+ Renders an input with type "week".
+ """
+
+ input_type = "week"
+ validation_attrs = ["required", "max", "min", "step"]
+
+
+class TimeInput(Input):
+ """
+ Renders an input with type "time".
+ """
+
+ input_type = "time"
+ validation_attrs = ["required", "max", "min", "step"]
+
+
+class DateTimeLocalInput(Input):
+ """
+ Renders an input with type "datetime-local".
+ """
+
+ input_type = "datetime-local"
+ validation_attrs = ["required", "max", "min", "step"]
+
+
+class NumberInput(Input):
+ """
+ Renders an input with type "number".
+ """
+
+ input_type = "number"
+ validation_attrs = ["required", "max", "min", "step"]
+
+ def __init__(self, step=None, min=None, max=None):
+ self.step = step
+ self.min = min
+ self.max = max
+
+ def __call__(self, field, **kwargs):
+ if self.step is not None:
+ kwargs.setdefault("step", self.step)
+ if self.min is not None:
+ kwargs.setdefault("min", self.min)
+ if self.max is not None:
+ kwargs.setdefault("max", self.max)
+ return super().__call__(field, **kwargs)
+
+
+class RangeInput(Input):
+ """
+ Renders an input with type "range".
+ """
+
+ input_type = "range"
+ validation_attrs = ["required", "max", "min", "step"]
+
+ def __init__(self, step=None):
+ self.step = step
+
+ def __call__(self, field, **kwargs):
+ if self.step is not None:
+ kwargs.setdefault("step", self.step)
+ return super().__call__(field, **kwargs)
+
+
+class ColorInput(Input):
+ """
+ Renders an input with type "color".
+ """
+
+ input_type = "color"
diff --git a/src/wtforms/widgets/html5.py b/src/wtforms/widgets/html5.py
deleted file mode 100644
index 2a9ea76..0000000
--- a/src/wtforms/widgets/html5.py
+++ /dev/null
@@ -1,143 +0,0 @@
-from .core import Input
-
-__all__ = (
- "ColorInput",
- "DateInput",
- "DateTimeInput",
- "DateTimeLocalInput",
- "EmailInput",
- "MonthInput",
- "NumberInput",
- "RangeInput",
- "SearchInput",
- "TelInput",
- "TimeInput",
- "URLInput",
- "WeekInput",
-)
-
-
-class SearchInput(Input):
- """
- Renders an input with type "search".
- """
-
- input_type = "search"
-
-
-class TelInput(Input):
- """
- Renders an input with type "tel".
- """
-
- input_type = "tel"
-
-
-class URLInput(Input):
- """
- Renders an input with type "url".
- """
-
- input_type = "url"
-
-
-class EmailInput(Input):
- """
- Renders an input with type "email".
- """
-
- input_type = "email"
-
-
-class DateTimeInput(Input):
- """
- Renders an input with type "datetime".
- """
-
- input_type = "datetime"
-
-
-class DateInput(Input):
- """
- Renders an input with type "date".
- """
-
- input_type = "date"
-
-
-class MonthInput(Input):
- """
- Renders an input with type "month".
- """
-
- input_type = "month"
-
-
-class WeekInput(Input):
- """
- Renders an input with type "week".
- """
-
- input_type = "week"
-
-
-class TimeInput(Input):
- """
- Renders an input with type "time".
- """
-
- input_type = "time"
-
-
-class DateTimeLocalInput(Input):
- """
- Renders an input with type "datetime-local".
- """
-
- input_type = "datetime-local"
-
-
-class NumberInput(Input):
- """
- Renders an input with type "number".
- """
-
- input_type = "number"
-
- def __init__(self, step=None, min=None, max=None):
- self.step = step
- self.min = min
- self.max = max
-
- def __call__(self, field, **kwargs):
- if self.step is not None:
- kwargs.setdefault("step", self.step)
- if self.min is not None:
- kwargs.setdefault("min", self.min)
- if self.max is not None:
- kwargs.setdefault("max", self.max)
- return super().__call__(field, **kwargs)
-
-
-class RangeInput(Input):
- """
- Renders an input with type "range".
- """
-
- input_type = "range"
-
- def __init__(self, step=None):
- self.step = step
-
- def __call__(self, field, **kwargs):
- if self.step is not None:
- kwargs.setdefault("step", self.step)
- return super().__call__(field, **kwargs)
-
-
-class ColorInput(Input):
- """
- Renders an input with type "color".
- """
-
- input_type = "color"
| HTML5 widgets by default
This patch is based upon #467, the changes are in the last commit 44a1cec.
It fixes #594
| Use HTML 5 widgets
The HTML 5 widgets are kept in their own section and not used by default, but this distinction doesn't make sense today. "HTML 5" is just "HTML" now. No supported browser doesn't understand those input types, and ones that aren't supported fall back to text anyway.
I already sort of started this by making the required validators add the `required` flag, and I'm taking it further with #406 for more complex flags. Fields should default to using the more specific widgets where possible. | wtforms/wtforms | diff --git a/tests/test_fields.py b/tests/test_fields.py
index f36ce71..0986534 100644
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -119,7 +119,7 @@ class TestFlags:
def test_existing_values(self, flags):
assert flags.required is True
assert "required" in flags
- assert flags.optional is False
+ assert flags.optional is None
assert "optional" not in flags
def test_assignment(self, flags):
@@ -1373,3 +1373,111 @@ class TestHTML5Fields:
if field.data != item["data"]:
tmpl = "Field {key} data mismatch: {field.data!r} != {data!r}"
raise AssertionError(tmpl.format(field=field, **item))
+
+
+class TestFieldValidatorsTest:
+ class F(Form):
+ v1 = [validators.Length(min=1)]
+ v2 = [validators.Length(min=1, max=3)]
+ string1 = StringField(validators=v1)
+ string2 = StringField(validators=v2)
+ password1 = PasswordField(validators=v1)
+ password2 = PasswordField(validators=v2)
+ textarea1 = TextAreaField(validators=v1)
+ textarea2 = TextAreaField(validators=v2)
+ search1 = SearchField(validators=v1)
+ search2 = SearchField(validators=v2)
+
+ v3 = [validators.NumberRange(min=1)]
+ v4 = [validators.NumberRange(min=1, max=3)]
+ integer1 = IntegerField(validators=v3)
+ integer2 = IntegerField(validators=v4)
+ integerrange1 = IntegerRangeField(validators=v3)
+ integerrange2 = IntegerRangeField(validators=v4)
+ decimal1 = DecimalField(validators=v3)
+ decimal2 = DecimalField(validators=v4)
+ decimalrange1 = DecimalRangeField(validators=v3)
+ decimalrange2 = DecimalRangeField(validators=v4)
+
+ def test_minlength_maxlength(self):
+ form = self.F()
+ assert (
+ form.string1()
+ == '<input id="string1" minlength="1" name="string1" type="text" value="">'
+ )
+
+ assert (
+ form.string2() == '<input id="string2" maxlength="3" minlength="1"'
+ ' name="string2" type="text" value="">'
+ )
+
+ assert (
+ form.password1() == '<input id="password1" minlength="1"'
+ ' name="password1" type="password" value="">'
+ )
+
+ assert (
+ form.password2() == '<input id="password2" maxlength="3" minlength="1"'
+ ' name="password2" type="password" value="">'
+ )
+
+ assert (
+ form.textarea1() == '<textarea id="textarea1" minlength="1"'
+ ' name="textarea1">\r\n</textarea>'
+ )
+
+ assert (
+ form.textarea2() == '<textarea id="textarea2" maxlength="3" minlength="1"'
+ ' name="textarea2">\r\n</textarea>'
+ )
+
+ assert (
+ form.search1() == '<input id="search1" minlength="1"'
+ ' name="search1" type="search" value="">'
+ )
+
+ assert (
+ form.search2() == '<input id="search2" maxlength="3" minlength="1"'
+ ' name="search2" type="search" value="">'
+ )
+
+ def test_min_max(self):
+ form = self.F()
+ assert (
+ form.integer1()
+ == '<input id="integer1" min="1" name="integer1" type="number" value="">'
+ )
+ assert (
+ form.integer2() == '<input id="integer2" max="3" min="1"'
+ ' name="integer2" type="number" value="">'
+ )
+
+ assert (
+ form.integerrange1() == '<input id="integerrange1" min="1"'
+ ' name="integerrange1" type="range" value="">'
+ )
+
+ assert (
+ form.integerrange2() == '<input id="integerrange2" max="3" min="1"'
+ ' name="integerrange2" type="range" value="">'
+ )
+
+ assert (
+ form.decimal1() == '<input id="decimal1" min="1"'
+ ' name="decimal1" step="any" type="number" value="">'
+ )
+
+ assert (
+ form.decimal2() == '<input id="decimal2" max="3" min="1"'
+ ' name="decimal2" step="any" type="number" value="">'
+ )
+
+ assert (
+ form.decimalrange1() == '<input id="decimalrange1" min="1"'
+ ' name="decimalrange1" step="any" type="range" value="">'
+ )
+
+ assert (
+ form.decimalrange2() == '<input id="decimalrange2" max="3" min="1"'
+ ' name="decimalrange2" step="any" type="range" value="">'
+ )
diff --git a/tests/test_validators.py b/tests/test_validators.py
index dd4613c..4e373ff 100644
--- a/tests/test_validators.py
+++ b/tests/test_validators.py
@@ -31,7 +31,7 @@ def test_data_required(dummy_form, dummy_field):
validator = data_required()
dummy_field.data = "foobar"
validator(dummy_form, dummy_field)
- assert validator.field_flags == ("required",)
+ assert validator.field_flags == {"required": True}
@pytest.mark.parametrize("bad_val", [None, "", " ", "\t\t"])
@@ -85,7 +85,7 @@ def test_input_required(dummy_form, dummy_field):
dummy_field.raw_data = ["foobar"]
validator(dummy_form, dummy_field)
- assert validator.field_flags == ("required",)
+ assert validator.field_flags == {"required": True}
def test_input_required_raises(dummy_form, dummy_field):
@@ -141,7 +141,7 @@ def test_input_optional_raises(data_v, raw_data_v, dummy_form, dummy_field):
with pytest.raises(StopValidation):
validator(dummy_form, dummy_field)
- assert validator.field_flags == ("optional",)
+ assert validator.field_flags == {"optional": True}
dummy_field.errors = ["Invalid Integer Value"]
assert len(dummy_field.errors) == 1
diff --git a/tests/test_widgets.py b/tests/test_widgets.py
index 9bedec6..a9b7cd3 100644
--- a/tests/test_widgets.py
+++ b/tests/test_widgets.py
@@ -7,14 +7,14 @@ from wtforms.widgets.core import HiddenInput
from wtforms.widgets.core import html_params
from wtforms.widgets.core import Input
from wtforms.widgets.core import ListWidget
+from wtforms.widgets.core import NumberInput
from wtforms.widgets.core import PasswordInput
from wtforms.widgets.core import RadioInput
+from wtforms.widgets.core import RangeInput
from wtforms.widgets.core import Select
from wtforms.widgets.core import TableWidget
from wtforms.widgets.core import TextArea
from wtforms.widgets.core import TextInput
-from wtforms.widgets.html5 import NumberInput
-from wtforms.widgets.html5 import RangeInput
class TestHTMLParams:
| [
"tests/test_fields.py::TestDefaults::test",
"tests/test_fields.py::TestLabel::test",
"tests/test_fields.py::TestLabel::test_auto_label",
"tests/test_fields.py::TestLabel::test_override_for",
"tests/test_fields.py::TestLabel::test_escaped_label_text",
"tests/test_fields.py::TestFlags::test_existing_values"... | [] | {
"base_image_name": "python_base_310",
"docker_specs": {
"_variant": null,
"bazel_version": null,
"bun_version": null,
"cargo_version": null,
"deno_version": null,
"docker_version": null,
"erlang_version": null,
"gcc_version": null,
"go_version": null,
"helm_version": null,
"java_version": null,
"jdk_version": null,
"llvm_version": null,
"lua_version": null,
"luajit_version": null,
"neovim_version": null,
"node_version": null,
"npm_version": null,
"nvim_version": null,
"pnpm_version": null,
"python_image": "python_base_310",
"python_version": null,
"redis_version": null,
"ruby_version": null,
"rust_version": null,
"rustc_version": null,
"solana_version": null,
"sqlite_version": null
},
"install": [
"pip install -q -e .[email] pytest babel"
],
"log_parser": "parse_log_pytest",
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning tests/test_fields.py tests/test_validators.py tests/test_widgets.py"
} | {
"llm_metadata": {
"code": "A",
"confidence": 0.96,
"detected_issues": {
"B1": false,
"B2": false,
"B3": false,
"B4": false,
"B5": false,
"B6": false
},
"difficulty": "medium",
"external_urls": [],
"intent_completeness": "complete",
"pr_categories": [
"core_feat"
],
"reasoning": "The issue requests default use of HTML5 widgets and flag handling changes, which the test patch verifies by updating expectations for flags, widget imports, and field defaults. The tests now match these new requirements, showing alignment without contradictory or missing assertions. No signals of B-category problems (no unrelated test coupling, naming mismatches, external dependencies, ambiguous specs, extra patch artifacts, or hidden domain knowledge) are present. Therefore the task is well‑specified and solvable.",
"test_alignment_issues": []
},
"num_modified_files": 8,
"num_modified_lines": 340,
"pr_author": "azmeuk",
"pr_labels": [],
"pr_url": null
} |
a9b06a635a7d3458c8e2ed2b10cc3fd1e02b5f37 | 2021-03-03 15:16:02 | docker.io/swerebenchv2/webpack-contrib-copy-webpack-plugin:590-a9b06a6 | webpack-contrib__copy-webpack-plugin-590 | Function: pattern.priority
Location: src/options.json (pattern object schema) and documentation README.md
Inputs: number priority – optional numeric value; defaults to 0 if omitted. Must be a finite number.
Outputs: The value is stored on the pattern and used by CopyPlugin to order asset emission; higher numbers are emitted later (thus can overwrite earlier copies when `force` is true).
Description: Specifies the copy priority for a given pattern. Assets from patterns with larger priority are processed after those with lower values, allowing later copies to overwrite earlier ones when the `force` option is enabled.
| js | MIT | diff --git a/README.md b/README.md
index af0b3ea..b20837a 100644
--- a/README.md
+++ b/README.md
@@ -85,6 +85,7 @@ module.exports = {
| [`filter`](#filter) | `{Function}` | `undefined` | Allows to filter copied assets. |
| [`toType`](#totype) | `{String}` | `undefined` | Determinate what is `to` option - directory, file or template. |
| [`force`](#force) | `{Boolean}` | `false` | Overwrites files already in `compilation.assets` (usually added by other plugins/loaders). |
+| [`priority`](#priority) | `{Number}` | `0` | Allows you to specify the copy priority. |
| [`transform`](#transform) | `{Object}` | `undefined` | Allows to modify the file contents. Enable `transform` caching. You can use `{ transform: {cache: { key: 'my-cache-key' }} }` to invalidate the cache. |
| [`noErrorOnMissing`](#noerroronmissing) | `{Boolean}` | `false` | Doesn't generate an error on missing file(s). |
| [`info`](#info) | `{Object\|Function}` | `undefined` | Allows to add assets info. |
@@ -462,6 +463,41 @@ module.exports = {
};
```
+#### `priority`
+
+Type: `Number`
+Default: `0`
+
+Allows to specify the priority of copying files with the same destination name.
+Files for patterns with higher priority will be copied later.
+To overwrite files, the [`force`](#force) option must be enabled.
+
+**webpack.config.js**
+
+```js
+module.exports = {
+ plugins: [
+ new CopyPlugin({
+ patterns: [
+ // Сopied second and will overwrite "dir_2/file.txt"
+ {
+ from: "dir_1/file.txt",
+ to: "newfile.txt",
+ force: true,
+ priority: 10,
+ },
+ // Сopied first
+ {
+ from: "dir_2/file.txt",
+ to: "newfile.txt",
+ priority: 5,
+ },
+ ],
+ }),
+ ],
+};
+```
+
#### `transform`
Type: `Function|Object`
diff --git a/src/index.js b/src/index.js
index 7d7d462..ad77115 100644
--- a/src/index.js
+++ b/src/index.js
@@ -70,6 +70,7 @@ class CopyPlugin {
}
static async runPattern(
+ assetMap,
compiler,
compilation,
logger,
@@ -313,7 +314,13 @@ class CopyPlugin {
path.relative(compiler.context, absoluteFilename)
);
- return { absoluteFilename, sourceFilename, filename, toType };
+ return {
+ absoluteFilename,
+ sourceFilename,
+ filename,
+ toType,
+ priority: pattern.priority || 0,
+ };
})
);
@@ -322,7 +329,13 @@ class CopyPlugin {
try {
assets = await Promise.all(
files.map(async (file) => {
- const { absoluteFilename, sourceFilename, filename, toType } = file;
+ const {
+ absoluteFilename,
+ sourceFilename,
+ filename,
+ toType,
+ priority,
+ } = file;
const info =
typeof pattern.info === "function"
? pattern.info(file) || {}
@@ -578,6 +591,12 @@ class CopyPlugin {
result.filename = normalizePath(result.filename);
}
+ if (!assetMap.has(priority)) {
+ assetMap.set(priority, []);
+ }
+
+ assetMap.get(priority).push(result);
+
// eslint-disable-next-line consistent-return
return result;
})
@@ -612,13 +631,14 @@ class CopyPlugin {
async (unusedAssets, callback) => {
logger.log("starting to add additional assets...");
- let assets;
+ const assetMap = new Map();
try {
- assets = await Promise.all(
+ await Promise.all(
this.patterns.map((item, index) =>
limit(async () =>
CopyPlugin.runPattern(
+ assetMap,
compiler,
compilation,
logger,
@@ -637,10 +657,12 @@ class CopyPlugin {
return;
}
+ const assets = [...assetMap.entries()].sort((a, b) => a[0] - b[0]);
+
// Avoid writing assets inside `p-limit`, because it creates concurrency.
// It could potentially lead to an error - 'Multiple assets emit different content to the same filename'
assets
- .reduce((acc, val) => acc.concat(val), [])
+ .reduce((acc, val) => acc.concat(val[1]), [])
.filter(Boolean)
.forEach((asset) => {
const {
diff --git a/src/options.json b/src/options.json
index 68f7272..725ff76 100644
--- a/src/options.json
+++ b/src/options.json
@@ -33,6 +33,9 @@
"force": {
"type": "boolean"
},
+ "priority": {
+ "type": "number"
+ },
"info": {
"anyOf": [
{
| Feat: added `priority` option
<!--
HOLY CRAP a Pull Request. We ❤️ those!
If you remove or skip this template, you'll make the 🐼 sad and the mighty god
of Github will appear and pile-drive the close button from a great height
while making animal noises.
Please place an x (no spaces!) in all [ ] that apply
-->
This PR contains a:
- [ ] **bugfix**
- [x] new **feature**
- [ ] **code refactor**
- [x] **test update** <!-- if bug or feature is checked, this should be too -->
- [ ] **typo fix**
- [x] **metadata update**
### Motivation / Use-Case
Fixed #318
### Breaking Changes
No
### Additional Info
No
| [Feature] Add order option
Hello,
In a project I am developing, I have an issue with copying files with the same name from multiple sources.
Configuration of copy webpack plugin is as follows:
```
new CopyWebpackPlugin([
{ from: 'node_modules/engine/static', test: /\.(css|html|png)$/, force: true },
{ from: 'node_modules/subengine/static', test: /\.(css|html|png)$/, force: true },
{ from: './static', test: /\.(css|html|png)$/, force: true },
]),
```
The project has two dependencies, let's call them `engine` and `subengine`. They are both bundled within node_modules.
Each of these has its own graphical assets. In case the file with an exact same name and path is in more than one repo, then one from "project" is more important than one from `subengine`, and one from `subengine` is more important than file from `engine`.
Let's say each of these contains an `abc.png` file in its own `static` folder. The intended result is to have `abc.png` come from projects's own `./static` folder, but it instead, the one from `subengine` is used.
HOWEVER.... which is where the fun begins...
If I do this:
```
new CopyWebpackPlugin([
{ from: 'node_modules/engine/static', test: /\.(css|html|png)$/, force: true },
{ from: 'node_modules/subengine/static', test: /\.(css|html|png)$/, force: true },
{ from: './static', test: /\.(css|html|png)$/, force: true },
], {debug: 'debug'}),
```
...then the order is correct, and `abc.png` is taken from project's `static` folder.
This might be random behavior and just a coincidence, but it really seems having debug on fixes the issue every time.
I am using:
`"webpack": "~4.17.2",` (I would like not to update further for now because then the build breaks elsewhere)
`"copy-webpack-plugin": "^4.6.0",`
Build on Windows 10, Node 8.4.0 | webpack-contrib/copy-webpack-plugin | diff --git a/test/__snapshots__/validate-options.test.js.snap b/test/__snapshots__/validate-options.test.js.snap
index a08f0ef..fd384cb 100644
--- a/test/__snapshots__/validate-options.test.js.snap
+++ b/test/__snapshots__/validate-options.test.js.snap
@@ -14,7 +14,7 @@ exports[`validate options should throw an error on the "options" option with "{"
exports[`validate options should throw an error on the "patterns" option with "" value 1`] = `
"Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
- options.patterns should be an array:
- [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
+ [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, priority?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
`;
exports[`validate options should throw an error on the "patterns" option with "[""]" value 1`] = `
@@ -40,7 +40,7 @@ exports[`validate options should throw an error on the "patterns" option with "[
exports[`validate options should throw an error on the "patterns" option with "[{"from":"dir","info":"string"}]" value 1`] = `
"Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
- options.patterns[0] should be one of these:
- non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, info?, transform?, transformPath?, noErrorOnMissing? }
+ non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, priority?, info?, transform?, transformPath?, noErrorOnMissing? }
Details:
* options.patterns[0].info should be one of these:
object { … } | function
@@ -53,7 +53,7 @@ exports[`validate options should throw an error on the "patterns" option with "[
exports[`validate options should throw an error on the "patterns" option with "[{"from":"dir","info":true}]" value 1`] = `
"Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
- options.patterns[0] should be one of these:
- non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, info?, transform?, transformPath?, noErrorOnMissing? }
+ non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, priority?, info?, transform?, transformPath?, noErrorOnMissing? }
Details:
* options.patterns[0].info should be one of these:
object { … } | function
@@ -88,7 +88,7 @@ exports[`validate options should throw an error on the "patterns" option with "[
exports[`validate options should throw an error on the "patterns" option with "[{"from":"test.txt","to":"dir","context":"context","transform":true}]" value 1`] = `
"Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
- options.patterns[0] should be one of these:
- non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, info?, transform?, transformPath?, noErrorOnMissing? }
+ non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, priority?, info?, transform?, transformPath?, noErrorOnMissing? }
Details:
* options.patterns[0].transform should be one of these:
function | object { transformer?, cache? }
@@ -103,10 +103,25 @@ exports[`validate options should throw an error on the "patterns" option with "[
- options.patterns[0].context should be a string."
`;
+exports[`validate options should throw an error on the "patterns" option with "[{"from":"test.txt","to":"dir","priority":"5"}]" value 1`] = `
+"Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
+ - options.patterns[0].priority should be a number."
+`;
+
+exports[`validate options should throw an error on the "patterns" option with "[{"from":"test.txt","to":"dir","priority":true}]" value 1`] = `
+"Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
+ - options.patterns[0].priority should be a number."
+`;
+
+exports[`validate options should throw an error on the "patterns" option with "[{"from":"test.txt","to":"dir"}]" value 1`] = `
+"Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
+ - options.patterns[0].priority should be a number."
+`;
+
exports[`validate options should throw an error on the "patterns" option with "[{"from":"test.txt","to":true,"context":"context"}]" value 1`] = `
"Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
- options.patterns[0] should be one of these:
- non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, info?, transform?, transformPath?, noErrorOnMissing? }
+ non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, priority?, info?, transform?, transformPath?, noErrorOnMissing? }
Details:
* options.patterns[0].to should be one of these:
string | function
@@ -134,71 +149,71 @@ exports[`validate options should throw an error on the "patterns" option with "[
exports[`validate options should throw an error on the "patterns" option with "{}" value 1`] = `
"Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
- options.patterns should be an array:
- [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
+ [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, priority?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
`;
exports[`validate options should throw an error on the "patterns" option with "true" value 1`] = `
"Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
- options.patterns should be an array:
- [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
+ [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, priority?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
`;
exports[`validate options should throw an error on the "patterns" option with "true" value 2`] = `
"Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
- options.patterns should be an array:
- [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
+ [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, priority?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
`;
exports[`validate options should throw an error on the "patterns" option with "undefined" value 1`] = `
"Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
- options misses the property 'patterns'. Should be:
- [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
+ [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, priority?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
`;
exports[`validate options should throw an error on the "unknown" option with "/test/" value 1`] = `
"Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
- options misses the property 'patterns'. Should be:
- [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
+ [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, priority?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
`;
exports[`validate options should throw an error on the "unknown" option with "[]" value 1`] = `
"Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
- options misses the property 'patterns'. Should be:
- [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
+ [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, priority?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
`;
exports[`validate options should throw an error on the "unknown" option with "{"foo":"bar"}" value 1`] = `
"Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
- options misses the property 'patterns'. Should be:
- [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
+ [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, priority?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
`;
exports[`validate options should throw an error on the "unknown" option with "{}" value 1`] = `
"Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
- options misses the property 'patterns'. Should be:
- [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
+ [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, priority?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
`;
exports[`validate options should throw an error on the "unknown" option with "1" value 1`] = `
"Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
- options misses the property 'patterns'. Should be:
- [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
+ [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, priority?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
`;
exports[`validate options should throw an error on the "unknown" option with "false" value 1`] = `
"Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
- options misses the property 'patterns'. Should be:
- [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
+ [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, priority?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
`;
exports[`validate options should throw an error on the "unknown" option with "test" value 1`] = `
"Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
- options misses the property 'patterns'. Should be:
- [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
+ [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, priority?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
`;
exports[`validate options should throw an error on the "unknown" option with "true" value 1`] = `
"Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
- options misses the property 'patterns'. Should be:
- [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
+ [non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, priority?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)"
`;
diff --git a/test/priority-option.test.js b/test/priority-option.test.js
new file mode 100644
index 0000000..cd95427
--- /dev/null
+++ b/test/priority-option.test.js
@@ -0,0 +1,57 @@
+import { run } from "./helpers/run";
+
+describe("priority option", () => {
+ it("should copy without specifying priority option", (done) => {
+ run({
+ expectedAssetKeys: [],
+ patterns: [
+ {
+ from: "dir (86)/file.txt",
+ to: "newfile.txt",
+ force: true,
+ },
+ {
+ from: "file.txt",
+ to: "newfile.txt",
+ force: true,
+ },
+ ],
+ })
+ .then(({ stats }) => {
+ const { info } = stats.compilation.getAsset("newfile.txt");
+
+ expect(info.sourceFilename).toEqual("file.txt");
+
+ done();
+ })
+ .catch(done);
+ });
+
+ it("should copy with specifying priority option", (done) => {
+ run({
+ expectedAssetKeys: [],
+ patterns: [
+ {
+ from: "dir (86)/file.txt",
+ to: "newfile.txt",
+ force: true,
+ priority: 10,
+ },
+ {
+ from: "file.txt",
+ to: "newfile.txt",
+ force: true,
+ priority: 5,
+ },
+ ],
+ })
+ .then(({ stats }) => {
+ const { info } = stats.compilation.getAsset("newfile.txt");
+
+ expect(info.sourceFilename).toEqual("dir (86)/file.txt");
+
+ done();
+ })
+ .catch(done);
+ });
+});
diff --git a/test/validate-options.test.js b/test/validate-options.test.js
index 7b85e15..26ffbdc 100644
--- a/test/validate-options.test.js
+++ b/test/validate-options.test.js
@@ -133,6 +133,13 @@ describe("validate options", () => {
},
},
],
+ [
+ {
+ from: "test.txt",
+ to: "dir",
+ priority: 5,
+ },
+ ],
],
failure: [
// eslint-disable-next-line no-undefined
@@ -242,6 +249,27 @@ describe("validate options", () => {
filter: "test",
},
],
+ [
+ {
+ from: "test.txt",
+ to: "dir",
+ priority: "5",
+ },
+ ],
+ [
+ {
+ from: "test.txt",
+ to: "dir",
+ priority: () => {},
+ },
+ ],
+ [
+ {
+ from: "test.txt",
+ to: "dir",
+ priority: true,
+ },
+ ],
],
},
options: {
| [
"should successfully validate the \"patterns\" option with \"[{\"from\":\"test.txt\",\"to\":\"dir\",\"priority\":5}]\" value",
"should throw an error on the \"patterns\" option with \"undefined\" value",
"should throw an error on the \"patterns\" option with \"true\" value",
"should throw an error on the \"pa... | [
"should exported",
"should successfully validate the \"patterns\" option with \"[\"test.txt\"]\" value",
"should successfully validate the \"patterns\" option with \"[\"test.txt\",\"test-other.txt\"]\" value",
"should successfully validate the \"patterns\" option with \"[\"test.txt\",{\"from\":\"test.txt\",\"... | {
"base_image_name": "node_16",
"docker_specs": {
"_variant": "js_2",
"bazel_version": null,
"bun_version": null,
"cargo_version": null,
"deno_version": null,
"docker_version": null,
"erlang_version": null,
"gcc_version": null,
"go_version": null,
"helm_version": null,
"java_version": null,
"jdk_version": null,
"llvm_version": null,
"lua_version": null,
"luajit_version": null,
"neovim_version": null,
"node_version": "16",
"npm_version": null,
"nvim_version": null,
"pnpm_version": null,
"python_image": null,
"python_version": null,
"redis_version": null,
"ruby_version": null,
"rust_version": null,
"rustc_version": null,
"solana_version": null,
"sqlite_version": null
},
"install": [
"npm ci"
],
"log_parser": "parse_log_js_4",
"test_cmd": "npm run test:only -- --verbose --no-color"
} | {
"llm_metadata": {
"code": "A",
"confidence": 0.97,
"detected_issues": {
"B1": false,
"B2": false,
"B3": false,
"B4": false,
"B5": false,
"B6": false
},
"difficulty": "medium",
"external_urls": [],
"intent_completeness": "complete",
"pr_categories": [
"core_feat"
],
"reasoning": "The issue requests a new `priority` option to control order of copied assets, with clear expected behavior and acceptance criteria. The provided tests verify schema validation and runtime precedence, matching the described functionality, so they are aligned. No signals of B‑category problems are present. Therefore the task is a clean, well‑specified new feature.",
"test_alignment_issues": []
},
"num_modified_files": 3,
"num_modified_lines": 66,
"pr_author": "cap-Bernardito",
"pr_labels": [],
"pr_url": null
} |
ab9e33a5f9fdb02c57141412867a4ec985135aa7 | 2018-12-13 14:02:33 | docker.io/swerebenchv2/crawler-commons-crawler-commons:227-ab9e33a | crawler-commons__crawler-commons-227 | No new interfaces are introduced. | java | Apache-2.0 | diff --git a/CHANGES.txt b/CHANGES.txt
index 3baa9bc..848fb68 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,6 +1,7 @@
Crawler-Commons Change Log
Current Development 0.11-SNAPSHOT (yyyy-mm-dd)
+- [Sitemaps] Sitemap index: stop URL at closing </loc> (sebastian-nagel, kkrugler) #213
- [Sitemaps] Allow empty price in video sitemaps (sebastian-nagel) #221
- [Sitemaps] In case of the use of a different locale, price tag can be formatted with ',' instead of '.' leading to a NPE (goldenlink) #220
- [Sitemaps] Add support for sitemap extensions (tuxnco, sebastian-nagel) #35, #36, #149, #162
diff --git a/src/main/java/crawlercommons/sitemaps/sax/DelegatorHandler.java b/src/main/java/crawlercommons/sitemaps/sax/DelegatorHandler.java
index 32767ef..d42b9c6 100644
--- a/src/main/java/crawlercommons/sitemaps/sax/DelegatorHandler.java
+++ b/src/main/java/crawlercommons/sitemaps/sax/DelegatorHandler.java
@@ -208,4 +208,14 @@ public class DelegatorHandler extends DefaultHandler {
delegate.fatalError(e);
}
}
+
+ public static boolean isAllBlank(CharSequence charSeq) {
+ for (int i = 0; i < charSeq.length(); i++) {
+ if (!Character.isWhitespace(charSeq.charAt(i))) {
+ return false;
+ }
+ }
+ return true;
+ }
+
}
diff --git a/src/main/java/crawlercommons/sitemaps/sax/XMLHandler.java b/src/main/java/crawlercommons/sitemaps/sax/XMLHandler.java
index d1fcfa0..91b6c5c 100644
--- a/src/main/java/crawlercommons/sitemaps/sax/XMLHandler.java
+++ b/src/main/java/crawlercommons/sitemaps/sax/XMLHandler.java
@@ -94,12 +94,9 @@ class XMLHandler extends DelegatorHandler {
// flush any unclosed or missing URL element
if (loc.length() > 0 && ("loc".equals(localName) || "url".equals(localName))) {
- // check whether loc isn't white space only
- for (int i = 0; i < loc.length(); i++) {
- if (!Character.isWhitespace(loc.charAt(i))) {
- maybeAddSiteMapUrl();
- return;
- }
+ if (!isAllBlank(loc)) {
+ maybeAddSiteMapUrl();
+ return;
}
loc = new StringBuilder();
if ("url".equals(localName)) {
diff --git a/src/main/java/crawlercommons/sitemaps/sax/XMLIndexHandler.java b/src/main/java/crawlercommons/sitemaps/sax/XMLIndexHandler.java
index 84d87ca..6c73d43 100644
--- a/src/main/java/crawlercommons/sitemaps/sax/XMLIndexHandler.java
+++ b/src/main/java/crawlercommons/sitemaps/sax/XMLIndexHandler.java
@@ -67,6 +67,19 @@ class XMLIndexHandler extends DelegatorHandler {
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
+ // flush any unclosed or missing <sitemap> element
+ if (loc.length() > 0 && ("loc".equals(localName) || "sitemap".equals(localName))) {
+ if (!isAllBlank(loc)) {
+ maybeAddSiteMap();
+ return;
+ }
+ loc = new StringBuilder();
+ if ("sitemap".equals(localName)) {
+ // reset also attributes
+ locClosed = false;
+ lastMod = null;
+ }
+ }
}
public void endElement(String uri, String localName, String qName) throws SAXException {
| Sitemap index: stop URL at closing </loc>
(fixes #213)
At start of a `<loc>` element auto-close any "unclosed" `<sitemap>` element and add the sitemap if there is a valid URL from the previous `<loc>` element. | [Sitemaps] Sitemap index: stop URL at closing </loc>
(cf. [Nutch mailing list](https://lists.apache.org/thread.html/8ebcffbe2bd8edafb6030e4f28fceee07aee08a1ce06a94755ee8d74@%3Cuser.nutch.apache.org%3E)
With #153 the sitemaps SAX parser handles sitemaps with missing or not properly closed <url> elements. This should be also done for sitemap indexes, e.g.:
```
<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex>
<sitemap>
<loc>https://www.example.orgl/sitemap1.xml</loc>
<loc>https://www.example.org/sitemap2.xml</loc>
</sitemap>
</sitemapindex>
```
| crawler-commons/crawler-commons | diff --git a/src/test/java/crawlercommons/sitemaps/SiteMapParserTest.java b/src/test/java/crawlercommons/sitemaps/SiteMapParserTest.java
index 10fc53c..270ea0a 100644
--- a/src/test/java/crawlercommons/sitemaps/SiteMapParserTest.java
+++ b/src/test/java/crawlercommons/sitemaps/SiteMapParserTest.java
@@ -274,6 +274,53 @@ public class SiteMapParserTest {
assertNotNull("Sitemap " + sitemap + " not found in sitemap index", sm.getSitemap(new URL(sitemap)));
}
+ @Test
+ public void testUnclosedSitemapIndexFile() throws UnknownFormatException, IOException {
+ SiteMapParser parser = new SiteMapParser();
+ StringBuilder scontent = new StringBuilder();
+ scontent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") //
+ .append("<sitemapindex>") //
+ .append(" <sitemap>") //
+ .append(" <loc>https://www.example.org/sitemap1.xml</loc>") //
+ .append(" <loc>https://www.example.org/sitemap2.xml</loc>") //
+ .append(" </sitemap>") //
+ .append("</sitemapindex>");
+ byte[] content = scontent.toString().getBytes(UTF_8);
+ URL url = new URL("http://www.example.com/sitemapindex.xml");
+
+ AbstractSiteMap asm = parser.parseSiteMap(content, url);
+ assertEquals(true, asm.isIndex());
+ assertEquals(true, asm instanceof SiteMapIndex);
+ SiteMapIndex sm = (SiteMapIndex) asm;
+ assertEquals(2, sm.getSitemaps().size());
+ String urlSecondSitemap = "https://www.example.org/sitemap2.xml";
+ AbstractSiteMap secondSitemap = sm.getSitemap(new URL(urlSecondSitemap));
+ assertNotNull("Sitemap " + urlSecondSitemap + " not found in sitemap index", secondSitemap);
+
+ // check reset of attributes (lastmod) when "autoclosing" <sitemap>
+ // elements
+ scontent = new StringBuilder();
+ scontent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") //
+ .append("<sitemapindex>\n") //
+ .append(" <sitemap>\n") //
+ .append(" <loc>https://www.example.org/sitemap1.xml</loc>\n") //
+ .append(" <lastmod>2004-10-01T18:23:17+00:00</lastmod>\n") //
+ .append(" <loc>https://www.example.org/sitemap2.xml</loc>\n") //
+ .append(" <loc>https://www.example.org/sitemap3.xml</loc>\n") //
+ .append(" <lastmod>2005-11-02T19:24:18+00:00</lastmod>\n") //
+ .append(" </sitemap>\n") //
+ .append("</sitemapindex>");
+ content = scontent.toString().getBytes(UTF_8);
+ asm = parser.parseSiteMap(content, url);
+ assertEquals(true, asm.isIndex());
+ assertEquals(true, asm instanceof SiteMapIndex);
+ sm = (SiteMapIndex) asm;
+ assertEquals(3, sm.getSitemaps().size());
+ secondSitemap = sm.getSitemap(new URL(urlSecondSitemap));
+ assertNotNull("Sitemap " + urlSecondSitemap + " not found in sitemap index", secondSitemap);
+ assertNull("Sitemap " + urlSecondSitemap + " without modification date", secondSitemap.getLastModified());
+ }
+
@Test
public void testSitemapGZ() throws UnknownFormatException, IOException {
SiteMapParser parser = new SiteMapParser();
| [
"crawlercommons.sitemaps.SiteMapParserTest",
"---NO TEST NAME FOUND YET---"
] | [
"crawlercommons.domains.EffectiveTldFinderPSLTest",
"crawlercommons.domains.EffectiveTldFinderTest",
"crawlercommons.domains.PaidLevelDomainTest",
"crawlercommons.domains.SuffixTrieTest",
"crawlercommons.filters.basic.BasicURLNormalizerTest",
"crawlercommons.mimetypes.MimeTypeDetectorTest",
"crawlercomm... | {
"base_image_name": "java_21",
"docker_specs": {
"_variant": null,
"bazel_version": null,
"bun_version": null,
"cargo_version": null,
"deno_version": null,
"docker_version": null,
"erlang_version": null,
"gcc_version": null,
"go_version": null,
"helm_version": null,
"java_version": "21",
"jdk_version": null,
"llvm_version": null,
"lua_version": null,
"luajit_version": null,
"neovim_version": null,
"node_version": null,
"npm_version": null,
"nvim_version": null,
"pnpm_version": null,
"python_image": null,
"python_version": null,
"redis_version": null,
"ruby_version": null,
"rust_version": null,
"rustc_version": null,
"solana_version": null,
"sqlite_version": null
},
"install": [
"mvn compile -q",
"mvn test-compile -q"
],
"log_parser": "parse_java_mvn",
"test_cmd": "mvn test -B --no-transfer-progress -Dsurefire.printSummary=true"
} | {
"llm_metadata": {
"code": "A",
"confidence": 0.87,
"detected_issues": {
"B1": false,
"B2": false,
"B3": false,
"B4": false,
"B5": false,
"B6": false
},
"difficulty": "medium",
"external_urls": [
"https://lists.apache.org/thread.html/8ebcffbe2bd8edafb6030e4f28fceee07aee08a1ce06a94755ee8d74@%3Cuser.nutch.apache.org%3E"
],
"intent_completeness": "complete",
"pr_categories": [
"minor_bug"
],
"reasoning": "The issue requests that the sitemap index parser gracefully handle missing or unclosed <loc> elements, mirroring behavior added for regular sitemaps. The added tests directly verify that the parser treats the input as an index, counts the correct number of sitemap URLs, and resets per‑sitemap attributes when an implicit closure occurs, which aligns with the described intent. No test‑suite coupling, naming expectations, external dependencies, or ambiguous specifications are present, so the task is cleanly solvable. Therefore the classification is A (solvable).",
"test_alignment_issues": []
},
"num_modified_files": 4,
"num_modified_lines": 27,
"pr_author": "sebastian-nagel",
"pr_labels": [],
"pr_url": null
} |
c5f472ef62f6307521cb1fe8a76a204438a6eee0 | 2021-04-16 22:30:50 | docker.io/swerebenchv2/dtolnay-cxx:839-c5f472e | dtolnay__cxx-839 | Method: CxxVector<T>.push(self: Pin<&mut Self>, value: T)
Location: src/cxx_vector.rs (impl block for CxxVector)
Inputs: a pinned mutable reference to a CxxVector holding a trivial extern type `T` (e.g., `f64`, `Shared`), and an owned `value` of type `T`. `T` must satisfy `ExternType<Kind = Trivial>`.
Outputs: `()` – the call mutates the underlying C++ `std::vector<T>` by appending the element; no return value.
Description: Appends `value` to the back of the vector. The method creates a `ManuallyDrop<T>` wrapper, then forwards to the hidden FFI routine `__push_back`, which invokes C++ `std::vector::push_back` and destroys the temporary on the Rust side. Use it when you need to grow a `CxxVector` from Rust with element types that can be passed by value.
| rust | Apache-2.0 | diff --git a/gen/src/builtin.rs b/gen/src/builtin.rs
index eaaa08d1..7ac9209c 100644
--- a/gen/src/builtin.rs
+++ b/gen/src/builtin.rs
@@ -30,6 +30,7 @@ pub struct Builtins<'a> {
pub relocatable: bool,
pub friend_impl: bool,
pub is_complete: bool,
+ pub destroy: bool,
pub deleter_if: bool,
pub content: Content<'a>,
}
@@ -334,6 +335,14 @@ pub(super) fn write(out: &mut OutFile) {
writeln!(out, "}};");
}
+ if builtin.destroy {
+ out.next_section();
+ writeln!(out, "template <typename T>");
+ writeln!(out, "void destroy(T *ptr) {{");
+ writeln!(out, " ptr->~T();");
+ writeln!(out, "}}");
+ }
+
if builtin.deleter_if {
out.next_section();
writeln!(out, "template <bool> struct deleter_if {{");
diff --git a/gen/src/write.rs b/gen/src/write.rs
index 7285a64a..f9627d36 100644
--- a/gen/src/write.rs
+++ b/gen/src/write.rs
@@ -1823,6 +1823,8 @@ fn write_cxx_vector(out: &mut OutFile, key: NamedImplKey) {
let instance = element.to_mangled(out.types);
out.include.cstddef = true;
+ out.include.utility = true;
+ out.builtin.destroy = true;
writeln!(
out,
@@ -1838,6 +1840,16 @@ fn write_cxx_vector(out: &mut OutFile, key: NamedImplKey) {
);
writeln!(out, " return &(*s)[pos];");
writeln!(out, "}}");
+ if out.types.is_maybe_trivial(element) {
+ writeln!(
+ out,
+ "void cxxbridge1$std$vector${}$push_back(::std::vector<{}> *v, {} *value) noexcept {{",
+ instance, inner, inner,
+ );
+ writeln!(out, " v->push_back(::std::move(*value));");
+ writeln!(out, " ::rust::destroy(value);");
+ writeln!(out, "}}");
+ }
out.include.memory = true;
write_unique_ptr_common(out, UniquePtr::CxxVector(element));
diff --git a/macro/src/expand.rs b/macro/src/expand.rs
index ee82e267..5ff5f8ef 100644
--- a/macro/src/expand.rs
+++ b/macro/src/expand.rs
@@ -1537,6 +1537,7 @@ fn expand_cxx_vector(
let prefix = format!("cxxbridge1$std$vector${}$", resolve.name.to_symbol());
let link_size = format!("{}size", prefix);
let link_get_unchecked = format!("{}get_unchecked", prefix);
+ let link_push_back = format!("{}push_back", prefix);
let unique_ptr_prefix = format!(
"cxxbridge1$unique_ptr$std$vector${}$",
resolve.name.to_symbol(),
@@ -1553,6 +1554,28 @@ fn expand_cxx_vector(
let end_span = explicit_impl.map_or(key.end_span, |explicit| explicit.brace_token.span);
let unsafe_token = format_ident!("unsafe", span = begin_span);
+ let can_pass_element_by_value = types.is_maybe_trivial(elem);
+ let push_back_method = if can_pass_element_by_value {
+ Some(quote_spanned! {end_span=>
+ #[doc(hidden)]
+ unsafe fn __push_back(
+ this: ::std::pin::Pin<&mut ::cxx::CxxVector<Self>>,
+ value: &mut ::std::mem::ManuallyDrop<Self>,
+ ) {
+ extern "C" {
+ #[link_name = #link_push_back]
+ fn __push_back #impl_generics(
+ this: ::std::pin::Pin<&mut ::cxx::CxxVector<#elem #ty_generics>>,
+ value: &mut ::std::mem::ManuallyDrop<#elem #ty_generics>,
+ );
+ }
+ __push_back(this, value);
+ }
+ })
+ } else {
+ None
+ };
+
quote_spanned! {end_span=>
#unsafe_token impl #impl_generics ::cxx::private::VectorElement for #elem #ty_generics {
#[doc(hidden)]
@@ -1575,6 +1598,7 @@ fn expand_cxx_vector(
}
__get_unchecked(v, pos)
}
+ #push_back_method
#[doc(hidden)]
fn __unique_ptr_null() -> *mut ::std::ffi::c_void {
extern "C" {
diff --git a/src/cxx.cc b/src/cxx.cc
index c0ef7389..f1b8ad81 100644
--- a/src/cxx.cc
+++ b/src/cxx.cc
@@ -427,6 +427,13 @@ using isize_if_unique =
} // namespace cxxbridge1
} // namespace rust
+namespace {
+template <typename T>
+void destroy(T *ptr) {
+ ptr->~T();
+}
+} // namespace
+
extern "C" {
void cxxbridge1$unique_ptr$std$string$null(
std::unique_ptr<std::string> *ptr) noexcept {
@@ -491,6 +498,13 @@ static_assert(sizeof(std::string) <= kMaxExpectedWordsInString * sizeof(void *),
ptr->~unique_ptr(); \
}
+#define STD_VECTOR_TRIVIAL_OPS(RUST_TYPE, CXX_TYPE) \
+ void cxxbridge1$std$vector$##RUST_TYPE##$push_back( \
+ std::vector<CXX_TYPE> *v, CXX_TYPE *value) noexcept { \
+ v->push_back(std::move(*value)); \
+ destroy(value); \
+ }
+
#define RUST_VEC_EXTERNS(RUST_TYPE, CXX_TYPE) \
void cxxbridge1$rust_vec$##RUST_TYPE##$new( \
rust::Vec<CXX_TYPE> *ptr) noexcept; \
@@ -603,10 +617,13 @@ static_assert(sizeof(std::string) <= kMaxExpectedWordsInString * sizeof(void *),
MACRO(f32, float) \
MACRO(f64, double)
-#define FOR_EACH_STD_VECTOR(MACRO) \
+#define FOR_EACH_TRIVIAL_STD_VECTOR(MACRO) \
FOR_EACH_NUMERIC(MACRO) \
MACRO(usize, std::size_t) \
- MACRO(isize, rust::isize) \
+ MACRO(isize, rust::isize)
+
+#define FOR_EACH_STD_VECTOR(MACRO) \
+ FOR_EACH_TRIVIAL_STD_VECTOR(MACRO) \
MACRO(string, std::string)
#define FOR_EACH_RUST_VEC(MACRO) \
@@ -627,6 +644,7 @@ static_assert(sizeof(std::string) <= kMaxExpectedWordsInString * sizeof(void *),
extern "C" {
FOR_EACH_STD_VECTOR(STD_VECTOR_OPS)
+FOR_EACH_TRIVIAL_STD_VECTOR(STD_VECTOR_TRIVIAL_OPS)
FOR_EACH_RUST_VEC(RUST_VEC_EXTERNS)
FOR_EACH_SHARED_PTR(SHARED_PTR_OPS)
} // extern "C"
diff --git a/src/cxx_vector.rs b/src/cxx_vector.rs
index 16433417..23f7621d 100644
--- a/src/cxx_vector.rs
+++ b/src/cxx_vector.rs
@@ -8,7 +8,7 @@ use core::ffi::c_void;
use core::fmt::{self, Debug};
use core::iter::FusedIterator;
use core::marker::{PhantomData, PhantomPinned};
-use core::mem;
+use core::mem::{self, ManuallyDrop};
use core::pin::Pin;
use core::ptr;
use core::slice;
@@ -146,6 +146,22 @@ where
pub fn iter_mut(self: Pin<&mut Self>) -> IterMut<T> {
IterMut { v: self, index: 0 }
}
+
+ /// Appends an element to the back of the vector.
+ ///
+ /// Matches the behavior of C++ [std::vector\<T\>::push_back][push_back].
+ ///
+ /// [push_back]: https://en.cppreference.com/w/cpp/container/vector/push_back
+ pub fn push(self: Pin<&mut Self>, value: T)
+ where
+ T: ExternType<Kind = Trivial>,
+ {
+ let mut value = ManuallyDrop::new(value);
+ unsafe {
+ // C++ calls move constructor followed by destructor on `value`.
+ T::__push_back(self, &mut value);
+ }
+ }
}
/// Iterator over elements of a `CxxVector` by shared reference.
@@ -296,6 +312,14 @@ pub unsafe trait VectorElement: Sized {
#[doc(hidden)]
unsafe fn __get_unchecked(v: *mut CxxVector<Self>, pos: usize) -> *mut Self;
#[doc(hidden)]
+ unsafe fn __push_back(v: Pin<&mut CxxVector<Self>>, value: &mut ManuallyDrop<Self>) {
+ // Opaque C type vector elements do not get this method because they can
+ // never exist by value on the Rust side of the bridge.
+ let _ = v;
+ let _ = value;
+ unreachable!()
+ }
+ #[doc(hidden)]
fn __unique_ptr_null() -> *mut c_void;
#[doc(hidden)]
unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void;
@@ -307,8 +331,24 @@ pub unsafe trait VectorElement: Sized {
unsafe fn __unique_ptr_drop(repr: *mut c_void);
}
+macro_rules! vector_element_push_back {
+ (opaque, $segment:expr, $ty:ty) => {};
+ (trivial, $segment:expr, $ty:ty) => {
+ #[doc(hidden)]
+ unsafe fn __push_back(v: Pin<&mut CxxVector<$ty>>, value: &mut ManuallyDrop<$ty>) {
+ extern "C" {
+ attr! {
+ #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$push_back")]
+ fn __push_back(_: Pin<&mut CxxVector<$ty>>, _: &mut ManuallyDrop<$ty>);
+ }
+ }
+ __push_back(v, value);
+ }
+ };
+}
+
macro_rules! impl_vector_element {
- ($segment:expr, $name:expr, $ty:ty) => {
+ ($kind:ident, $segment:expr, $name:expr, $ty:ty) => {
const_assert_eq!(1, mem::align_of::<CxxVector<$ty>>());
unsafe impl VectorElement for $ty {
@@ -336,6 +376,7 @@ macro_rules! impl_vector_element {
}
__get_unchecked(v, pos)
}
+ vector_element_push_back!($kind, $segment, $ty);
#[doc(hidden)]
fn __unique_ptr_null() -> *mut c_void {
extern "C" {
@@ -396,7 +437,7 @@ macro_rules! impl_vector_element {
macro_rules! impl_vector_element_for_primitive {
($ty:ident) => {
- impl_vector_element!(stringify!($ty), stringify!($ty), $ty);
+ impl_vector_element!(trivial, stringify!($ty), stringify!($ty), $ty);
};
}
@@ -413,4 +454,4 @@ impl_vector_element_for_primitive!(isize);
impl_vector_element_for_primitive!(f32);
impl_vector_element_for_primitive!(f64);
-impl_vector_element!("string", "CxxString", CxxString);
+impl_vector_element!(opaque, "string", "CxxString", CxxString);
| Add CxxVector::push in Rust
Closes #778. | CxxVector::push_back
Adding push_back/pop functionality (and other mutation functionality) to `CxxVector` would be helpful for `CxxVector`s containing types that rust can obtain (e.g. `CxxVector<CxxString>` or `CxxVector<SharedPtr<T>>`). Similarly, `CxxVector::new()` or `CxxVector::default()` would be helpful to create them from Rust. | dtolnay/cxx | diff --git a/tests/ffi/tests.cc b/tests/ffi/tests.cc
index 214bfcd6..98069b28 100644
--- a/tests/ffi/tests.cc
+++ b/tests/ffi/tests.cc
@@ -342,7 +342,7 @@ void c_take_unique_ptr_vector_u8(std::unique_ptr<std::vector<uint8_t>> v) {
}
void c_take_unique_ptr_vector_f64(std::unique_ptr<std::vector<double>> v) {
- if (v->size() == 4) {
+ if (v->size() == 5) {
cxx_test_suite_set_correct();
}
}
@@ -354,7 +354,7 @@ void c_take_unique_ptr_vector_string(
}
void c_take_unique_ptr_vector_shared(std::unique_ptr<std::vector<Shared>> v) {
- if (v->size() == 2) {
+ if (v->size() == 3) {
cxx_test_suite_set_correct();
}
}
diff --git a/tests/test.rs b/tests/test.rs
index c8204ce0..60e943f1 100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -153,12 +153,12 @@ fn test_c_take() {
check!(ffi::c_take_unique_ptr_vector_u8(
ffi::c_return_unique_ptr_vector_u8()
));
- check!(ffi::c_take_unique_ptr_vector_f64(
- ffi::c_return_unique_ptr_vector_f64()
- ));
- check!(ffi::c_take_unique_ptr_vector_shared(
- ffi::c_return_unique_ptr_vector_shared()
- ));
+ let mut vector = ffi::c_return_unique_ptr_vector_f64();
+ vector.pin_mut().push(9.0);
+ check!(ffi::c_take_unique_ptr_vector_f64(vector));
+ let mut vector = ffi::c_return_unique_ptr_vector_shared();
+ vector.pin_mut().push(ffi::Shared { z: 9 });
+ check!(ffi::c_take_unique_ptr_vector_shared(vector));
check!(ffi::c_take_ref_vector(&ffi::c_return_unique_ptr_vector_u8()));
let test_vec = [86_u8, 75_u8, 30_u8, 9_u8].to_vec();
check!(ffi::c_take_rust_vec(test_vec.clone()));
| [
"test_extern_c_function",
"test_impl_annotation",
"test_async_cxx_string",
"test_c_call_r",
"test_c_method_calls",
"test_c_callback",
"test_c_return",
"test_c_ns_method_calls",
"test_c_take",
"test_c_try_return",
"test_enum_representations",
"test_debug",
"test_extern_trivial",
"test_exter... | [] | {
"base_image_name": "rust_1.84",
"docker_specs": {
"_variant": null,
"bazel_version": null,
"bun_version": null,
"cargo_version": null,
"deno_version": null,
"docker_version": null,
"erlang_version": null,
"gcc_version": "12.2.0",
"go_version": null,
"helm_version": null,
"java_version": null,
"jdk_version": null,
"llvm_version": null,
"lua_version": null,
"luajit_version": null,
"neovim_version": null,
"node_version": null,
"npm_version": null,
"nvim_version": null,
"pnpm_version": null,
"python_image": null,
"python_version": null,
"redis_version": null,
"ruby_version": null,
"rust_version": "1.89.0",
"rustc_version": null,
"solana_version": null,
"sqlite_version": null
},
"install": [
"curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y",
"export PATH=\"/root/.cargo/bin:$PATH\"",
"cargo build --release"
],
"log_parser": "parse_log_cargo",
"test_cmd": "cargo test --lib --bins --tests -- --nocapture"
} | {
"llm_metadata": {
"code": "B4",
"confidence": 0.78,
"detected_issues": {
"B1": false,
"B2": false,
"B3": false,
"B4": true,
"B5": false,
"B6": false
},
"difficulty": "medium",
"external_urls": [],
"intent_completeness": "partial",
"pr_categories": [
"core_feat"
],
"reasoning": "The issue requests push_back/pop (and constructors) for CxxVector but does not describe exact behavior or acceptance criteria; the tests encode the expected size changes after a push, which the issue never mentions, making the specification ambiguous. The tests align with a concrete implementation that the issue does not specify, indicating a primary B4 ambiguity. No other B‑category signals are evident.",
"test_alignment_issues": [
"Tests assert that after pushing an element the vector size becomes 5 (for f64) and 3 (for Shared), which the issue never describes.",
"Tests rely on a Rust‑side `push` method and a C++ `push_back` extern symbol that are not mentioned in the issue."
]
},
"num_modified_files": 5,
"num_modified_lines": 110,
"pr_author": "dtolnay",
"pr_labels": [],
"pr_url": null
} |
b829b78e37d1f0befe314f1683abfdb7bb2944f0 | 2025-05-28 07:56:39 | docker.io/swerebenchv2/gradleup-shadow:1448-b829b78 | gradleup__shadow-1448 | No new interfaces are introduced. | kotlin | Apache-2.0 | diff --git a/build.gradle.kts b/build.gradle.kts
index 896dc162c..e35e2c90e 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -36,8 +36,8 @@ kotlin {
explicitApi()
compilerOptions {
// https://docs.gradle.org/current/userguide/compatibility.html#kotlin
- @Suppress("DEPRECATION") // TODO: bump apiVersion to 2.0 to match Gradle 9.0
- apiVersion = KotlinVersion.KOTLIN_1_8
+ apiVersion = KotlinVersion.KOTLIN_2_0
+ languageVersion = apiVersion
jvmTarget = JvmTarget.JVM_11
freeCompilerArgs.addAll(
"-Xjvm-default=all",
diff --git a/docs/changes/README.md b/docs/changes/README.md
index 6cf66cde8..c41c2bb61 100644
--- a/docs/changes/README.md
+++ b/docs/changes/README.md
@@ -2,6 +2,11 @@
## [Unreleased](https://github.com/GradleUp/shadow/compare/9.0.0-beta14...HEAD) - 2025-xx-xx
+**Fixed**
+
+- Pin the plugin's Kotlin language level on 2.0. ([#1448](https://github.com/GradleUp/shadow/pull/1448))
+ The language level used in `9.0.0-beta14` is 2.2, which may cause compatibility issues for the plugins depending on
+ Shadow.
## [9.0.0-beta14](https://github.com/GradleUp/shadow/releases/tag/9.0.0-beta14) - 2025-05-28
diff --git a/src/main/kotlin/com/github/jengelman/gradle/plugins/shadow/transformers/PropertiesFileTransformer.kt b/src/main/kotlin/com/github/jengelman/gradle/plugins/shadow/transformers/PropertiesFileTransformer.kt
index 4e6d6f377..4f331a0c5 100644
--- a/src/main/kotlin/com/github/jengelman/gradle/plugins/shadow/transformers/PropertiesFileTransformer.kt
+++ b/src/main/kotlin/com/github/jengelman/gradle/plugins/shadow/transformers/PropertiesFileTransformer.kt
@@ -238,7 +238,6 @@ public open class PropertiesFileTransformer @Inject constructor(
public companion object {
@JvmStatic
public fun from(value: String): MergeStrategy {
- @OptIn(ExperimentalStdlibApi::class)
return entries.find { it.name.equals(value, ignoreCase = true) }
?: throw IllegalArgumentException("Unknown merge strategy: $value")
}
| - Closes #1436.
- Closes #1446.
---
- [x] [CHANGELOG](https://github.com/GradleUp/shadow/blob/main/docs/changes/README.md)'s "Unreleased" section has been updated, if applicable. | Trouble compiling against older kotlin versions
### Expected and Results
We'd expect at least support for kotlin versions in the Gradle 8 family, but we're seeing
```
Class 'com.github.jengelman.gradle.plugins.shadow.ShadowJavaPlugin' was compiled with an incompatible version of Kotlin. The actual metadata version is 2.1.0, but the compiler version 1.9.0 can read versions up to 2.0.0.
```
while compiling against Kotlin 1.9.20 and Gradle 8.6
### Related environment and versions
_No response_
### Reproduction steps
1. Create a gradle plugin
2. Set the gradle version to 8.14
3. Set the kotlin gradle plugin version to 1.9.25
4. Observe issue
```
`/example/gradle-shadow-old-kotlin/plugin/src/main/kotlin/org/example/GradleShadowOldKotlinPlugin.kt:17:17 Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The actual metadata version is 2.1.0, but the compiler version 1.9.0 can read versions up to 2.0.0.
The class is loaded from /Users/cwalker/.gradle/wrapper/dists/gradle-9.0.0-milestone-8-bin/9sf1y14o9rs7csri8q5psfb7a/gradle-9.0.0-milestone-8/lib/kotlin-stdlib-2.1.21.jar!/kotlin/Unit.class
```
### Anything else?
_No response_ | GradleUp/shadow | diff --git a/src/documentTest/kotlin/com/github/jengelman/gradle/plugins/shadow/DocCodeSnippetTest.kt b/src/documentTest/kotlin/com/github/jengelman/gradle/plugins/shadow/DocCodeSnippetTest.kt
index 1af8dc917..d5e06ffc9 100644
--- a/src/documentTest/kotlin/com/github/jengelman/gradle/plugins/shadow/DocCodeSnippetTest.kt
+++ b/src/documentTest/kotlin/com/github/jengelman/gradle/plugins/shadow/DocCodeSnippetTest.kt
@@ -10,7 +10,6 @@ import org.junit.jupiter.api.io.TempDir
class DocCodeSnippetTest {
- @OptIn(ExperimentalStdlibApi::class)
@TestFactory
fun provideDynamicTests(@TempDir root: Path): List<DynamicTest> {
val langExecutables = DslLang.entries.map { executor ->
| [
"[1] foo.properties, com.github.jengelman.gradle.plugins.shadow.transformers.PropertiesFileTransformerTest$Companion$$Lambda/0x00007f3ed0533748@14292d71, {foo=bar}, {FOO=baz}, {foo=bar, FOO=baz} (com.github.jengelman.gradle.plugins.shadow.transformers.PropertiesFileTransformerTest)",
"[2] foo.properties, com.gith... | [
"relocatePath() (com.github.jengelman.gradle.plugins.shadow.relocation.SimpleRelocatorTest)",
"relocateMavenFiles() (com.github.jengelman.gradle.plugins.shadow.relocation.SimpleRelocatorTest)",
"canRelocateIncludedSourceFile() (com.github.jengelman.gradle.plugins.shadow.relocation.SimpleRelocatorTest)",
"canR... | {
"base_image_name": "kotlin-jdk-21",
"docker_specs": {
"_variant": null,
"bazel_version": null,
"bun_version": null,
"cargo_version": null,
"deno_version": null,
"docker_version": null,
"erlang_version": null,
"gcc_version": null,
"go_version": null,
"helm_version": null,
"java_version": null,
"jdk_version": "21",
"llvm_version": null,
"lua_version": null,
"luajit_version": null,
"neovim_version": null,
"node_version": null,
"npm_version": null,
"nvim_version": null,
"pnpm_version": null,
"python_image": null,
"python_version": null,
"redis_version": null,
"ruby_version": null,
"rust_version": null,
"rustc_version": null,
"solana_version": null,
"sqlite_version": null
},
"install": [
"./gradlew compileKotlin --no-daemon --console=plain",
"./gradlew compileTestKotlin --no-daemon --console=plain"
],
"log_parser": "parse_log_gradlew_v1",
"test_cmd": "./gradlew test --rerun-tasks --no-daemon --console=plain && find . -name 'TEST-*.xml' -path '*/test-results/*' -exec cat {} +"
} | {
"llm_metadata": {
"code": "A",
"confidence": 0.96,
"detected_issues": {
"B1": false,
"B2": false,
"B3": false,
"B4": false,
"B5": false,
"B6": false
},
"difficulty": "easy",
"external_urls": [],
"intent_completeness": "complete",
"pr_categories": [
"regression_bug"
],
"reasoning": "The issue reports that the Shadow plugin fails to compile with older Kotlin versions (e.g., Kotlin 1.9.x) due to metadata version incompatibility. The provided test patch removes an @OptIn annotation that is unavailable in those Kotlin versions, and the golden patch pins the Kotlin language level to 2.0 to ensure compatibility, directly addressing the reported problem. The tests verify successful compilation under the older Kotlin version, matching the stated requirement, and no B‑category signals are present, so the task is clearly solvable.",
"test_alignment_issues": []
},
"num_modified_files": 4,
"num_modified_lines": null,
"pr_author": "Goooler",
"pr_labels": null,
"pr_url": "https://github.com/GradleUp/shadow/pull/1448"
} |
aca99bc3c73eb6b2ae1eccd7ef76bbe1df96e3f5 | 2024-09-06 19:48:25 | docker.io/swerebenchv2/aio-libs-aiohttp:9047-aca99bc | aio-libs__aiohttp-9047 | "Method: TCPConnector._get_ssl_context(self, req: ClientRequest) -> Optional[ssl.SSLContext>\nLocati(...TRUNCATED) | python | custom-check-github | "diff --git a/CHANGES/9032.bugfix.rst b/CHANGES/9032.bugfix.rst\nnew file mode 100644\nindex 0000000(...TRUNCATED) | "[PR #9032/c693a816 backport][3.11] Fix Link-Local IPv6 Flags in the Resolver\n**This is a backport (...TRUNCATED) | "ClientSession.get() doesn't support hostname.\n### Describe the bug\r\n\r\nWhen using a URI with a (...TRUNCATED) | aio-libs/aiohttp | "diff --git a/tests/test_connector.py b/tests/test_connector.py\nindex 0129f0cc3..bbe77f2a7 100644\n(...TRUNCATED) | ["tests/test_connector.py::test_connection_del[pyloop]","tests/test_connector.py::test_connection_de(...TRUNCATED) | [] | {"base_image_name":"python_base_310","docker_specs":{"_variant":null,"bazel_version":null,"bun_versi(...TRUNCATED) | {"llm_metadata":{"code":"A","confidence":0.97,"detected_issues":{"B1":false,"B2":false,"B3":false,"B(...TRUNCATED) |
2ad5f638789af3e37a3a07ed3f4d4938a8209ed4 | 2024-08-15 19:30:10 | docker.io/swerebenchv2/bvanelli-actualpy:56-2ad5f63 | bvanelli__actualpy-56 | "Method: ActionType.SET_SPLIT_AMOUNT\nLocation: actual.rules (enum ActionType)\nInputs: None (enum m(...TRUNCATED) | python | MIT | "diff --git a/actual/__init__.py b/actual/__init__.py\nindex 3ae112c..564c3a7 100644\n--- a/actual/_(...TRUNCATED) | feat: Implement custom set split amount rules.
Closes #53 | "Operation ActionType.SET_SPLIT_AMOUNT not supported\n### Description\n\nI've a rule that given a ce(...TRUNCATED) | bvanelli/actualpy | "diff --git a/tests/test_rules.py b/tests/test_rules.py\nindex bc28ec9..71d22c4 100644\n--- a/tests/(...TRUNCATED) | ["tests/test_rules.py::test_category_rule","tests/test_rules.py::test_datetime_rule","tests/test_rul(...TRUNCATED) | [] | {"base_image_name":"python_base_310","docker_specs":{"_variant":null,"bazel_version":null,"bun_versi(...TRUNCATED) | {"llm_metadata":{"code":"A","confidence":0.97,"detected_issues":{"B1":false,"B2":false,"B3":false,"B(...TRUNCATED) |
a41f20979a19741f9de8b436ad46b6daa71e53e5 | 2022-02-26 13:26:47 | docker.io/swerebenchv2/box-project-box:644-a41f209 | box-project__box-644 | No new interfaces are introduced. | php | MIT | "diff --git a/src/DockerFileGenerator.php b/src/DockerFileGenerator.php\nindex e4a82edb..863ad7af 10(...TRUNCATED) | Add PHP 8.0 and 8.1 to DockerFileGenerator
Closes #630 | "Docker support with PHP 8\nAs latest version 3.16.0, Box is supposed to support both PHP 7.x and 8.(...TRUNCATED) | box-project/box | "diff --git a/tests/DockerFileGeneratorTest.php b/tests/DockerFileGeneratorTest.php\nindex a7211a4c.(...TRUNCATED) | ["Docblock Annotation Parser > It can parse php docblocks with data set #1 [0.12 ms]","Base Compacto(...TRUNCATED) | ["Docblock Annotation Parser > It can parse php docblocks with data set #0 [0.02 ms]","Docblock Anno(...TRUNCATED) | {"base_image_name":"php:8.3.16","docker_specs":{"_variant":null,"bazel_version":null,"bun_version":n(...TRUNCATED) | {"llm_metadata":{"code":"A","confidence":0.99,"detected_issues":{"B1":false,"B2":false,"B3":false,"B(...TRUNCATED) |
db37bd27a105006980e5a4788acc23c6de9225df | 2023-12-06 22:00:23 | docker.io/swerebenchv2/rust-bitcoin-rust-bitcoin:2255-db37bd2 | rust-bitcoin__rust-bitcoin-2255 | "Method: Script.minimal_non_dust(&self)\nLocation: impl Script in bitcoin::blockdata::script::borrow(...TRUNCATED) | rust | CC0-1.0 | "diff --git a/bitcoin/src/blockdata/script/borrowed.rs b/bitcoin/src/blockdata/script/borrowed.rs\ni(...TRUNCATED) | "Fix: TxOut::minimal_non_dust and Script::dust_value\nFixes #2192 \r\n\r\nTxOut::minimal_non_dust ha(...TRUNCATED) | "`Script::dust_value` method name disagrees with the documentation\nDust is a value that is not econ(...TRUNCATED) | rust-bitcoin/rust-bitcoin | "diff --git a/bitcoin/src/blockdata/script/tests.rs b/bitcoin/src/blockdata/script/tests.rs\nindex c(...TRUNCATED) | ["address::tests::invalid_address_parses_error","address::tests::test_fail_address_from_script","add(...TRUNCATED) | [] | {"base_image_name":"rust_1.84","docker_specs":{"_variant":null,"bazel_version":null,"bun_version":nu(...TRUNCATED) | {"llm_metadata":{"code":"A","confidence":0.97,"detected_issues":{"B1":false,"B2":false,"B3":false,"B(...TRUNCATED) |
SWE-rebench-V2
Dataset Summary
SWE-rebench-V2 is a curated dataset of software-engineering tasks derived from real GitHub issues and pull requests. The dataset contains 32,079 samples covering Python, Go, TypeScript, JavaScript, Rust, Java, PHP, Kotlin, Julia, Elixir, Scala, Swift, Dart, C, C++, C#, R, Clojure, OCaml, and Lua.
For log parser functions, base Dockerfiles, and the prompts used, please see https://github.com/SWE-rebench/SWE-rebench-V2
The detailed technical report is available at “SWE-rebench V2: Language-Agnostic SWE Task Collection at Scale”.
Quick Start
from datasets import load_dataset
ds = load_dataset("nebius/SWE-rebench-V2", split="train")
print(len(ds)) # 32079
Dataset Structure
| Field | Type | Description |
|---|---|---|
instance_id |
string |
Unique identifier for the instance |
repo |
string |
GitHub repository in owner/repo format |
base_commit |
string |
Git commit SHA of the base before the fix |
patch |
string |
The gold patch that resolves the issue |
test_patch |
string |
Diff adding or modifying tests that verify the fix |
problem_statement |
string |
Issue description the patch addresses |
pr_description |
string |
Full pull request description |
created_at |
int64 |
Unix timestamp (milliseconds) of the issue/PR creation |
image_name |
string |
Docker image name used for the evaluation environment |
language |
string |
Primary programming language of the repository |
interface |
string |
Description of the code interface changed by the patch |
license |
string |
SPDX license identifier of the repository |
FAIL_TO_PASS |
list[string] |
Test IDs that fail before the patch and pass after |
PASS_TO_PASS |
list[string] |
Test IDs that pass both before and after the patch |
install_config |
struct |
Configuration needed to reproduce the test environment |
meta |
struct |
Metadata and LLM-generated quality annotations |
License
The dataset is licensed under the Creative Commons Attribution 4.0 license. However, please respect the license of each specific repository on which a particular instance is based. To facilitate this, the license of each repository at the time of the commit is provided for every instance.
Citation
@misc{badertdinov2026swerebenchv2languageagnosticswe,
title={SWE-rebench V2: Language-Agnostic SWE Task Collection at Scale},
author={Ibragim Badertdinov and Maksim Nekrashevich and Anton Shevtsov and Alexander Golubev},
year={2026},
eprint={2602.23866},
archivePrefix={arXiv},
primaryClass={cs.SE},
url={https://arxiv.org/abs/2602.23866},
}
- Downloads last month
- 4,177