profile
viewpoint
Veetaha Veetaha Ukraine, Kyiv (hometown is Sumy) Vitalii Kryvenko a.k.a. Витаха

matklad/tom 21

tom: a format-preserving TOML parser in Rust

Veetaha/db-labs 2

My database studies labs

elastio/lambda-rust 0

🐳 🦀 a dockerized lambda build env for rust applications

Veetaha/advisory-db 0

Security advisory database for Rust crates published through crates.io

Veetaha/advisory-lock-rs 0

An advisory lock in Rust

Veetaha/air-hockey-game 0

Air hockey game made to accomplish a job application test.

Veetaha/alga 0

Abstract algebra for Rust.

Veetaha/amethyst 0

Data-oriented and data-driven game engine written in Rust

Veetaha/angular-electron 0

Ultra-fast bootstrapping with Angular 7 and Electron 4 (Typescript + SASS + Hot Reload) :speedboat:

Veetaha/api-guidelines 0

Rust API guidelines

Pull request review commentrust-analyzer/rust-analyzer

Allow to use a Github Auth token for fetching releases

 async function getServer(config: Config, state: PersistentState): Promise<string     await state.updateServerVersion(config.package.version);     return dest; }++async function performDownloadWithRetryDialog<T>(downloadFunc: () => Promise<T>, state: PersistentState): Promise<T> {+    while (true) {+        try {+            return await downloadFunc();+        } catch (e) {+            const selected = await vscode.window.showErrorMessage("Failed perform download: " + e.message, {}, {+                title: "Update Github Auth Token",+                updateToken: true,+            }, {+                title: "Retry download",+                retry: true,+            }, {+                title: "Dismiss",+            });++            if (selected?.updateToken) {+                await queryForGithubToken(state);+                continue;+            } else if (selected?.retry) {+                continue;+            }+            throw e;+        };+    }+}++async function queryForGithubToken(state: PersistentState): Promise<void> {+    const githubTokenOptions: vscode.InputBoxOptions = {+        value: state.githubToken,+        password: true,+        prompt: `+            This dialog allows to store a Github authorization token.+            The usage of an authorization token will increase the rate+            limit on the use of Github APIs and can thereby prevent getting+            throttled.+            Auth tokens can be created at https://github.com/settings/tokens`,+    };++    const newToken = await vscode.window.showInputBox(githubTokenOptions);+    if (newToken !== undefined) {

There should be something in the else branch I guess

Matthias247

comment created time in 14 hours

Pull request review commentrust-analyzer/rust-analyzer

Allow to use a Github Auth token for fetching releases

 export async function fetchRelease(      log.debug("Issuing request for released artifacts metadata to", requestUrl); -    const response = await fetch(requestUrl, { headers: { Accept: "application/vnd.github.v3+json" } });+    var headers: any = { Accept: "application/vnd.github.v3+json" };+    if (githubToken != null) {+        headers.Authorization = "token " + githubToken;+    }++    const response = await fetch(requestUrl, { headers: headers });
    const headers: Record<string, string> = { Accept: "application/vnd.github.v3+json" };
    if (githubToken != null) {
        headers.Authorization = "token " + githubToken;
    }

    const response = await fetch(requestUrl, { headers });
Matthias247

comment created time in 15 hours

Pull request review commentrust-analyzer/rust-analyzer

Allow to use a Github Auth token for fetching releases

 async function getServer(config: Config, state: PersistentState): Promise<string     await state.updateServerVersion(config.package.version);     return dest; }++async function performDownloadWithRetryDialog<T>(downloadFunc: () => Promise<T>, state: PersistentState): Promise<T> {+    while (true) {+        try {+            return await downloadFunc();+        } catch (e) {+            const selected = await vscode.window.showErrorMessage("Failed perform download: " + e.message, {}, {
            const selected = await vscode.window.showErrorMessage("Failed to download: " + e.message, {}, {
Matthias247

comment created time in 15 hours

Pull request review commentrust-analyzer/rust-analyzer

Allow to use a Github Auth token for fetching releases

 async function getServer(config: Config, state: PersistentState): Promise<string     await state.updateServerVersion(config.package.version);     return dest; }++async function performDownloadWithRetryDialog<T>(downloadFunc: () => Promise<T>, state: PersistentState): Promise<T> {
async function downloadWithRetryDialog<T>(state: PersistentState, downloadFunc: () => Promise<T>): Promise<T> {

The verbs perform and do seem redundant, I also recommend passing callbacks as the last parameter to be able to invoke it with a closure more cleanly

Matthias247

comment created time in 15 hours

PullRequestReviewEvent
PullRequestReviewEvent

created tagelastio/devx

tagv0.3.1

Collection of utilities for writing your own dev scripts

created time in a day

pull request commentelastio/devx

Release v0.3.1

bors r+

Veetaha

comment created time in a day

push eventelastio/devx

Veetaha

commit sha 5245cf3db1d7f68240ed8954a50d506a4458ae1a

Release v0.3.1

view details

push time in a day

pull request commentelastio/devx

Release v0.3.1

bors cancel

Veetaha

comment created time in a day

PR opened elastio/devx

Release v0.3.1

bors r+

+27 -17

0 comment

4 changed files

pr created time in a day

create barnchelastio/devx

branch : feat/release-v0.3.1

created branch time in a day

pull request commentelastio/devx

Add a method to set env vars, update simple_logger

bors r+

Veetaha

comment created time in a day

push eventelastio/devx

Veetaha

commit sha 5d1db939aeb2303b890f0b6855f8998f836a4d0e

Add a method to set env vars, update simple_logger

view details

push time in a day

PR opened elastio/devx

Add a method to set env vars, update simple_logger
+19 -3

0 comment

3 changed files

pr created time in a day

create barnchelastio/devx

branch : feat/add-env-vars-api

created branch time in a day

issue closedsoftprops/dynomite

Make tests data-driven and self-updating

💡 Feature description

Data-driven tests are declarative, they require very little manual maintenance effort and are easy to read. I propose to use expect-test, a magic library written by matklad (creator of rust-analyzer) to implement this. The tests are self-updating (i.e. if there is a breaking change in dynomite you don't have to manually update the expected values, expect-test will modify the source files for you. This is reminiscent of trybuild, which updates the expected stderr value of the test)

💻 Basic example

<!-- Include a basic code example if possible. Omit this section if not applicable. -->

The test will look like this:

let actual = Attribute::into_attr(Foo { value: 92 });
// We may add a fmt::Debug newtype on top off attribute value to reduce the verbosity (remove all the None from output)
// When writing new tests we use an empty clause: `expect![[]]`, after that we run the tests for `expect-test` to modify 
// the source file and fill in the expected value Debug representation
let expected = expect![["
    AttributeValue {
        M: Some({
            "value": AttributeValue { 
                 N: Some(92),
                 S: None,
                 ...
             }
        }),
        S: None,
        SS: None,
        ...
    }
"]];
expected.assert_debug_eq(&actual);

closed time in 5 days

Veetaha

issue commentsoftprops/dynomite

Make tests data-driven and self-updating

Hm, I see, I'm closing the issue then

Veetaha

comment created time in 5 days

issue openedrust-analyzer/rust-analyzer

Panic bad offset in goto_implementation for symbols form include!()

goto_implementation seems to panic of the on-hover symbol target comes from a file included via a macro include!("foo"):

In the following log, the offset 10835 most likely refers to the offset with all the macros expanded (i.e. include!() call replaced with the file contents), but for some goto_implementation::goto_implementation tries to look up a node in an unexpanded AST.

<details> <summary>Log</summary>

thread '<unnamed>' panicked at 'Bad offset: range 0..632 offset 10835', /home/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/rowan-0.10.0/src/cursor.rs:449:9
stack backtrace:
thread '<unnamed>' panicked at 'Bad offset: range 0..632 offset 10835', /home/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/rowan-0.10.0/src/cursor.rs:449:9
   0: backtrace::backtrace::libunwind::trace
             at /cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.46/src/backtrace/libunwind.rs:86
   1: backtrace::backtrace::trace_unsynchronized
             at /cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.46/src/backtrace/mod.rs:66
   2: std::sys_common::backtrace::_print_fmt
             at src/libstd/sys_common/backtrace.rs:78
   3: <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt
             at src/libstd/sys_common/backtrace.rs:59
   4: core::fmt::write
             at src/libcore/fmt/mod.rs:1076
   5: std::io::Write::write_fmt
             at src/libstd/io/mod.rs:1537
   6: std::sys_common::backtrace::_print
             at src/libstd/sys_common/backtrace.rs:62
   7: std::sys_common::backtrace::print
             at src/libstd/sys_common/backtrace.rs:49
   8: std::panicking::default_hook::{{closure}}
             at src/libstd/panicking.rs:198
   9: std::panicking::default_hook
             at src/libstd/panicking.rs:217
  10: std::panicking::rust_panic_with_hook
             at src/libstd/panicking.rs:526
  11: rust_begin_unwind
             at src/libstd/panicking.rs:437
  12: std::panicking::begin_panic_fmt
             at src/libstd/panicking.rs:391
  13: rowan::cursor::SyntaxNode::token_at_offset
  14: syntax::algo::ancestors_at_offset
  15: syntax::algo::find_node_at_offset
  16: ide::goto_implementation::goto_implementation
  17: ide::Analysis::goto_implementation
  18: core::ops::function::impls::<impl core::ops::function::FnMut<A> for &mut F>::call_mut
  19: <alloc::vec::Vec<T> as alloc::vec::SpecExtend<T,I>>::from_iter
  20: rust_analyzer::handlers::handle_hover
  21: <F as threadpool::FnBox>::call_box
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.

</details>

created time in 8 days

PR opened rust-analyzer/rust-analyzer

Feat/document consuming modifier

cc https://github.com/rust-analyzer/rust-analyzer/pull/5957/files

+4 -0

0 comment

1 changed file

pr created time in 8 days

push eventVeetaha/rust-analyzer

Veetaha

commit sha af8663f2e6926f9e6de5f1f8e5b0a508be543ff6

Document "consuming" semantic tokens modifier

view details

push time in 8 days

create barnchVeetaha/rust-analyzer

branch : feat/document-consuming-modifier

created branch time in 8 days

pull request commentsoftprops/dynomite

Add initial support for fat enums (internally-tagged representation)

This should be ready for the review. cc @softprops

Veetaha

comment created time in 8 days

Pull request review commentashleygwilliams/cargo-generate

Feat/graceful handle unknown variables and other errors during parsing

 pub(crate) fn walk_dir(         pbar.set_message(&filename.display().to_string());          if matcher.should_include(relative_path) {-            let new_contents = engine-                .clone()-                .parse_file(filename)?-                .render(&template)-                .with_context(|| {-                    format!(-                        "{} {} `{}`",-                        emoji::ERROR,-                        style("Error replacing placeholders").bold().red(),-                        style(filename.display()).bold()-                    )-                })?;-            fs::write(filename, new_contents).with_context(|| {-                format!(-                    "{} {} `{}`",-                    emoji::ERROR,-                    style("Error writing").bold().red(),-                    style(filename.display()).bold()-                )-            })?;+            let parsed_file = engine.clone().parse_file(filename);+            match parsed_file {+                Ok(parsed_file) => parse_and_replace(&template, filename, parsed_file)?,+                Err(e) => {+                    if verbose {+                        files_with_errors.push((filename.display().to_string(), e.clone()));+                    }+                }+            }         }     }+    if files_with_errors.len() > 0 {+        let warn = construct_substitution_warning(files_with_errors);+        println!("{}", warn);+    }      pbar.finish_and_clear();     Ok(()) }++fn parse_and_replace(+    context: &Object,+    filename: &Path,+    parsed_file: Template,+) -> Result<(), anyhow::Error> {
) -> anyhow::Result<()> {
sassman

comment created time in 9 days

Pull request review commentashleygwilliams/cargo-generate

Feat/graceful handle unknown variables and other errors during parsing

 pub(crate) fn walk_dir(         pbar.set_message(&filename.display().to_string());          if matcher.should_include(relative_path) {-            let new_contents = engine-                .clone()-                .parse_file(filename)?-                .render(&template)-                .with_context(|| {-                    format!(-                        "{} {} `{}`",-                        emoji::ERROR,-                        style("Error replacing placeholders").bold().red(),-                        style(filename.display()).bold()-                    )-                })?;-            fs::write(filename, new_contents).with_context(|| {-                format!(-                    "{} {} `{}`",-                    emoji::ERROR,-                    style("Error writing").bold().red(),-                    style(filename.display()).bold()-                )-            })?;+            let parsed_file = engine.clone().parse_file(filename);+            match parsed_file {+                Ok(parsed_file) => parse_and_replace(&template, filename, parsed_file)?,+                Err(e) => {+                    if verbose {+                        files_with_errors.push((filename.display().to_string(), e.clone()));+                    }+                }+            }         }     }+    if files_with_errors.len() > 0 {+        let warn = construct_substitution_warning(files_with_errors);+        println!("{}", warn);+    }      pbar.finish_and_clear();     Ok(()) }++fn parse_and_replace(+    context: &Object,+    filename: &Path,+    parsed_file: Template,+) -> Result<(), anyhow::Error> {+    let new_content = parse_file(context, filename, &parsed_file);+    fs::write(filename, new_content).with_context(|| {+        format!(+            "{} {} `{}`",+            emoji::ERROR,+            style("Error writing").bold().red(),+            style(filename.display()).bold()+        )+    })?;++    Ok(())+}++fn parse_file(context: &Object, filename: &Path, parsed_file: &Template) -> String {+    match parsed_file.render(context) {+        Ok(content) => content,+        Err(e) => {+            let msg = e.to_string();+            if msg.contains("requested variable") {+                // so, we miss a variable that is present in the file to render+                let requested_var =+                    regex::Regex::new(r"(?P<p>.*requested\svariable=)(?P<v>.*)").unwrap();+                let captures = requested_var.captures(msg.as_str()).unwrap();++                if let Some(Some(req_var)) = captures.iter().last() {+                    let missing_variable = req_var.as_str().to_string();+                    // try again with this variable added to the context+                    let mut context = context.clone();+                    context.insert(missing_variable.into(), Value::scalar("".to_string()));+                    // now let's parse again to see if we have all variables declared now+                    return parse_file(&context, filename, parsed_file);+                }+            }+            eprintln!(+                "{} {} `{}`",+                emoji::ERROR,+                style("Error replacing placeholders, file got only copied.")+                    .bold()+                    .red(),+                style(filename.display()).bold()+            );+            // fallback: take the file as it is, without substitutions+            fs::read_to_string(filename).unwrap()+        }+    }+}++fn construct_substitution_warning(files_with_errors: Vec<(String, liquid_core::Error)>) -> String {+    let mut msg = format!(+        "\n{} {}",+        emoji::WARN,+        style("Substitution skipped, found invalid syntax in\n")+            .bold()+            .red(),+    );+    for file_error in files_with_errors {+        msg.push_str("\t");+        msg.push_str(&file_error.0);+        msg.push_str("\n");+    }+    msg.push_str("\n");+    let info = format!("{}", style("Consider adding these files to a `cargo-generate.toml` in the template repo to skip substitution on these files.\n").bold());+    msg.push_str(&info);

This requires use std::fmt::Write at the top of the file, but:

    writeln!(msg, "{}", style("Consider adding these files to a `cargo-generate.toml` in the template repo to skip substitution on these files.").bold()).unwrap();
sassman

comment created time in 9 days

Pull request review commentashleygwilliams/cargo-generate

Feat/graceful handle unknown variables and other errors during parsing

 pub(crate) fn walk_dir(         pbar.set_message(&filename.display().to_string());          if matcher.should_include(relative_path) {-            let new_contents = engine-                .clone()-                .parse_file(filename)?-                .render(&template)-                .with_context(|| {-                    format!(-                        "{} {} `{}`",-                        emoji::ERROR,-                        style("Error replacing placeholders").bold().red(),-                        style(filename.display()).bold()-                    )-                })?;-            fs::write(filename, new_contents).with_context(|| {-                format!(-                    "{} {} `{}`",-                    emoji::ERROR,-                    style("Error writing").bold().red(),-                    style(filename.display()).bold()-                )-            })?;+            let parsed_file = engine.clone().parse_file(filename);+            match parsed_file {+                Ok(parsed_file) => parse_and_replace(&template, filename, parsed_file)?,+                Err(e) => {+                    if verbose {+                        files_with_errors.push((filename.display().to_string(), e.clone()));+                    }+                }+            }         }     }+    if files_with_errors.len() > 0 {
    if !files_with_errors.is_empty() {
sassman

comment created time in 9 days

PullRequestReviewEvent
PullRequestReviewEvent

issue commentrust-analyzer/rust-analyzer

[VSCode] getaddrinfo EAI_AGAIN

Not sure we can act more gracefully here, if the server download failed, the extension is pretty useless without it.

We may add code to retry the download with exponential backoff and provide a more specialized error message. Anyone interested may try to tackle this here: https://github.com/rust-analyzer/rust-analyzer/blob/7ba578ab1413505e960dda305cc322a29bc00ab3/editors/code/src/net.ts#L1-L151

mominul

comment created time in 9 days

push eventVeetaha/dynomite

Veetaha

commit sha 9e5c3fcd8b79cc4413f1d750b4fbeeb220ddb2d3

Add support for internally-tagged fat enums

view details

push time in 10 days

push eventVeetaha/dynomite

Veetaha

commit sha 40b9d87f1a70de3dd5ca49d717e50266cd8633ad

Cleanup From/IntoAttributes traits: Renamed `fn from_mut_attrs` to `fn from_attrs` and removed the previous impl. Now in order to convert items to/from attrs by consuming them users should use generated `TryFrom<Attributes>/Into<Attributes>` impls.

view details

push time in 10 days

pull request commentashleygwilliams/cargo-generate

Update the project to the latest world version

Done

Veetaha

comment created time in 11 days

push eventVeetaha/cargo-generate

Veetaha

commit sha 6205342fc0eda254b54ed8177faf5047e280f917

Run cargo fmt

view details

push time in 11 days

push eventVeetaha/cargo-generate

Veetaha

commit sha fdbfcb2086fdcd0aa6033efd262e52cae0cf0e41

Run cargo fmt

view details

push time in 11 days

push eventVeetaha/cargo-generate

Rebecca Turner

commit sha 8db4ec111a8e0fdb9ec4f8b74db1a8112afc9c3d

Support abbreviated owner/repo Git URL format The GitHub [hub] tool allows using `owner/repo` as an abbreviated form of `https://github.com/owner/repo.git`. This change supports that format with the `--git` command-line argument. It also improves the command-line argument documentation. [hub]: https://github.com/github/hub

view details

Rebecca Turner

commit sha ac49f180eb91a20d5115f7393e772bddee50067c

Improve assertion messages

view details

Rebecca Turner

commit sha ae8b1ad0c9114a2d717682220aa9e4f916532e5e

Disable a few asserts on Windows Backslashes strike again

view details

Antonin Carette

commit sha f886353144c354d19ec7d5aa684684c613e1d485

Merge branch 'master' into abbr-github

view details

Antonin Carette

commit sha a4e15fcd7b0ece266d2fdb235ed8d08233a21ccc

Merge branch 'master' into abbr-github

view details

k0pernicus

commit sha d7e725c50318de39151b1afe6fa0d77453592385

Updated mistakes when merging with master

view details

k0pernicus

commit sha f09eeeb37a433ea2e2969070f3f5831c8a2b92bb

Force the CLI to use branch 'main' in tests

view details

k0pernicus

commit sha c432492b6d03c0da69e5140d0cd97ce6fea6e9b3

Fixed linter issue

view details

Antonin Carette

commit sha d2bb2e5e21eb650d1d2f9e9470921799c7ff3c72

Merge pull request #242 from 9999years/abbr-github Support abbreviated `owner/repo` Git URL format

view details

Veetaha

commit sha da6c788d8f425acf65098138d23cdb691e7c57a4

Update the project to the latest word version * Update all dependencies version to latest ones * Remove `quicli` completely * Replace failure with anyhow * Update cargo authors copied code to latest cargo master * Fix clippy lints: * Replace &PathBuf to &Path in code * Remove `use crate_name` entires * Replace unexported `pub` with `pub(crate)` * Apply some cosmetic impl refactorings

view details

Veetaha

commit sha d837ed1fc25ce6cefa8fd1294ac9e2103c9c077c

Replace rustfmt-preview with stable rustfmt

view details

Veetaha

commit sha a60c6b98d992d1a9ff0148308bd540bdba0411f1

Use three slashes after the `file:` scheme, This is a small breaking change in cargo, because they no longer try to normalize urls: https://github.com/rust-lang/cargo/pull/7238

view details

Veetaha

commit sha 9c4f9198c1d0cd6e63fbabe1794f5c7b834e9afc

Git commit fix file:// scheme for unix now ;d

view details

Veetaha

commit sha 66ea0edac475dbc67cd9fef354c88f677ed1f63b

Run cargo fmt

view details

push time in 11 days

push eventVeetaha/cargo-generate

Veetaha

commit sha 70977f0b3508ba62a231c89546520a95f1fd440c

Run cargo fmt

view details

push time in 11 days

pull request commentashleygwilliams/cargo-generate

Update the project to the latest world version

Rebased

Veetaha

comment created time in 11 days

push eventVeetaha/cargo-generate

Rebecca Turner

commit sha 544d3ac17c01bf0d47f67ccdcdfe9d0d0e0430df

GitConfig::new : accept GitReference, not String This lets us specify more kinds of revisions, instead of being limited to branches.

view details

Rebecca Turner

commit sha 5d0adf6a1b2ac6a7a6d9001806eac0886d1a6d3c

Only set initial branch if given Currently, `git::init` always sets the `initial_head` to the string passed in with `--branch`, defaulting to `--master` if it's not given. By not setting it unless `--branch` is explicitly given, we respect the user's `config.defaultBranch`. Note that this has the (possibly?) confusing behavior of copying the branch name used for cloning the *template* repository into the newly-created repository.

view details

Rebecca Turner

commit sha cade86abfe70aaf2739b315201eb6527de96a876

Use FETCH_HEAD by default if --branch isn't given Instead of defaulting to `master`, checkout `FETCH_HEAD` (the default remote branch) if `--branch` isn't explicitly given on the command line.

view details

Rebecca Turner

commit sha f56c3b5538a5d87882dbb8aa0e73c17b43d096e2

Integration tests: explicitly set branch to main Add `--initial-branch=main` to the `git init` helper call in the integration tests; otherwise, the global `init.defaultBranch` setting in a user's Git config can cause all integration tests to fail.

view details

Rebecca Turner

commit sha 992babd9adf1c7b644cd037bb84ffd3c9430e705

Use `branch -m` instead of `init --initial-branch` `git init --initial-branch=...` is only supported on very new versions of Git, like, too new to be on AppVeyor. We therefore use `git branch --move main` after the first `git commit` to get the same effect on older Gits in our integration tests.

view details

Rebecca Turner

commit sha 6bd4e335b038eaf984e5ae46a1f9308ba49fb241

Add rust-cli-template to TEMPLATES.md (#239) * Add rust-cli-template to TEMPLATES.md * Remove spurious whitespace

view details

Antonin Carette

commit sha b9320b6a59a4210b43af055af9fb3a5e4413795a

Merge branch 'master' into use-head-branch

view details

Antonin Carette

commit sha c72a162559043c2606a9c29a43241fc091ccdffb

Merge pull request #241 from 9999years/use-head-branch Use default remote branch instead of `master`

view details

Veetaha

commit sha 386885b1727a275a21791a4adc30f7a1d6030371

Update the project to the latest word version * Update all dependencies version to latest ones * Remove `quicli` completely * Replace failure with anyhow * Update cargo authors copied code to latest cargo master * Fix clippy lints: * Replace &PathBuf to &Path in code * Remove `use crate_name` entires * Replace unexported `pub` with `pub(crate)` * Apply some cosmetic impl refactorings

view details

Veetaha

commit sha 575fc50f613b7fd4076908fd928845005013ee65

Replace rustfmt-preview with stable rustfmt

view details

Veetaha

commit sha 821c1b583fd787f8daa5df089dfa2f1456123d43

Use three slashes after the `file:` scheme, This is a small breaking change in cargo, because they no longer try to normalize urls: https://github.com/rust-lang/cargo/pull/7238

view details

Veetaha

commit sha f562ee0ec445046a653bc9789f33bd5fe70b46e8

Git commit fix file:// scheme for unix now ;d

view details

push time in 11 days

push eventVeetaha/dynomite

Veetaha

commit sha 4cf057ee30265c11b78fd2a2a3deb69636bf54c1

Cleanup From/IntoAttributes traits: Renamed `fn from_mut_attrs` to `fn from_attrs` and removed the previous impl. Now in order to convert items to/from attrs by consuming them users should use generated `TryFrom<Attributes>/Into<Attributes>` impls.

view details

push time in 11 days

push eventVeetaha/dynomite

Veetaha

commit sha 26147f43dbecb47526307da6feb090bb618c88fd

Cleanup From/IntoAttributes traits: Renamed `fn from_mut_attrs` to `fn from_attrs` and removed the previous impl. Now in order to convert items to/from attrs by consuming them users should use generated `TryFrom<Attributes>/Into<Attributes>` impls.

view details

push time in 11 days

push eventVeetaha/dynomite

Veetaha

commit sha 974e18bc7741bda9a6cd41902a9796bca2c944c6

Cleanup From/IntoAttributes traits: Renamed `fn from_mut_attrs` to `fn from_attrs` and removed the previous impl. Now in order to convert items to/from attrs by consuming them users should use generated `TryFrom<Attributes>/Into<Attributes>` impls.

view details

push time in 11 days

PR opened softprops/dynomite

Cleanup From/IntoAttributes traits

Blocked by:

  • #134
  • #136

What did you implement:

Renamed fn from_mut_attrs to fn from_attrs and removed the previous impl.

Now in order to convert items to/from attrs by consuming them users should use generated TryFrom<Attributes>/Into<Attributes> impls.

How did you verify your change:

Ran existing tests

What (if anything) would need to be called out in the CHANGELOG for the next release:

  • from_attrs now takes Attributes by a &mut reference, use try_from() for convenient consuming of the attr map
+701 -211

0 comment

14 changed files

pr created time in 11 days

create barnchVeetaha/dynomite

branch : feat/cleanup-from-into-attrs-traits

created branch time in 11 days

push eventVeetaha/dynomite

Veetaha

commit sha 86b63e3506390a508f2933436f72a70a7d905473

Add support for internally-tagged fat enums

view details

push time in 12 days

push eventVeetaha/dynomite

Veetaha

commit sha 3ec117bc5f5d626b6b2b5bb7491a34e7c2a3bfc9

Add support for internally-tagged fat enums

view details

push time in 12 days

push eventVeetaha/dynomite

Veetaha

commit sha c71047819271983af78263681680d69127d0f289

Add support for internally-tagged fat enums

view details

push time in 12 days

push eventVeetaha/dynomite

Veetaha

commit sha b78d02dae02374646ffa535650791d49c2639f78

Add support for internally-tagged fat enums

view details

push time in 12 days

push eventVeetaha/dynomite

Veetaha

commit sha 3c998ac469fc83313588e8fa5488b1acee06bcf4

Impl attribute for FromAttributes + IntoAttributes

view details

Veetaha

commit sha 4d7f9e6c4b8367f153ebbf12aed3f83578eb55c5

Add support for internally-tagged fat enums

view details

push time in 12 days

pull request commentsoftprops/dynomite

Implement Attribute for FromAttributes + IntoAttributes

@softprops this one should be easy to merge :)

Veetaha

comment created time in 12 days

push eventVeetaha/dynomite

Veetaha

commit sha 3c998ac469fc83313588e8fa5488b1acee06bcf4

Impl attribute for FromAttributes + IntoAttributes

view details

push time in 12 days

push eventVeetaha/dynomite

Veetaha

commit sha a6db30e50d52f8a1465847a187e210e8c8d74926

Add support for internally-tagged fat enums

view details

push time in 12 days

PR opened softprops/dynomite

Add initial support for fat enums (internally-tagged representation)

Internally tagged enums

The docs are pretty self-explanatory. This PR adds support for simple fat enums that have either one-element-tuple variants of the nested value of type T such that T: Attributes, or unit variants.

use dynomite::Attributes;

#[derive(Attributes)]
#[dynomite(tag = "kind")] // required to specify for fat enums
enum Shape {
    Rectangle(Rectangle),
    // Use `rename` to change the **value** of the tag for a particular variant
    // by default the tag for a particular variant is the name of the variant verbatim
    #[dynomite(rename = "my_circle")]
    Circle(Circle),
    Unknown,
}

#[derive(Attributes)]
struct Circle {
    radius: u32,
}

#[derive(Attributes)]
struct Rectangle {
    width: u32,
    height: u32,
}

These Rust definition correspond to the following representation in DynamoDB for each enum variant:

  • Rectangle:
    {
        "kind": "Rectangle",
        "width": 42,
        "height": 64
    }
    
  • Circle:
    {
        "kind": "my_circle",
        "radius": 54
    }
    
  • Unknown:
    {
        "kind": "Unknown"
    }
    

Closes: #131

How did you verify your change:

Added a unit test, trybuild tests and doc tests

What (if anything) would need to be called out in the CHANGELOG for the next release:

  • Add initial support for fat enums (only one-element tuple variants of T: Attributes values and unit variants)
+1094 -277

0 comment

20 changed files

pr created time in 12 days

push eventVeetaha/dynomite

Veetaha

commit sha 1f3f3559739771c1f08ab2f68235f64dcb4376b4

Add support for internally-tagged fat enums

view details

push time in 12 days

issue commentrust-lang/rustfmt

format_code_in_doc_comments removes parts of non-doc comments

I would add that the line comment is reformated to an ugly star-prefixed comment:

enum Foo {
    Bar,
    // a
    // b
}

   ↓ ↓ ↓ ↓ ↓ ↓

enum Foo {
    Bar,
    /* a
     * b */
}
vmx

comment created time in 12 days

push eventVeetaha/dynomite

Veetaha

commit sha 7336cfec8148f832ffec6f403fa540f62e2b5ad1

Impl attribute for FromAttributes + IntoAttributes

view details

Veetaha

commit sha 61a81517820846966f750903c515f99b4655df75

Add support for internally-tagged fat enums

view details

push time in 12 days

issue openedsoftprops/dynomite

Make tests data-driven and self-updating

💡 Feature description

Data-driven tests are declarative, they require very little manual maintenance effort and are easy to read. I propose to use expect-test, a magic library written by matklad (creator of rust-analyzer) to implement this. The tests are self-updating (i.e. if there is a breaking change in dynomite you don't have to manually update the expected values, expect-test will modify the source files for you. This is reminiscent of trybuild, which updates the expected stderr value of the test)

The test will look like this:

let actual = Attribute::into_attr(Foo { value: 92 });
// We may add a fmt::Debug newtype on top off attribute value to reduce the verbosity (remove all the None from output)
// When writing new tests we use an empty clause: `expect![[]]`, after that we run the tests for `expect-test` to modify 
// the source file and fill in the expected value Debug representation
let expected = expect![["
    AttributeValue {
        M: Some({
            "value": AttributeValue { 
                 N: Some(92),
                 S: None,
                 ...
             }
        }),
        S: None,
        SS: None,
        ...
    }
"]];
expected.assert_debug_eq(&actual);

💻 Basic example

<!-- Include a basic code example if possible. Omit this section if not applicable. -->

created time in 13 days

push eventVeetaha/dynomite

Veetaha

commit sha 7336cfec8148f832ffec6f403fa540f62e2b5ad1

Impl attribute for FromAttributes + IntoAttributes

view details

push time in 13 days

PR opened softprops/dynomite

Feat/impl attr for into from attrs

What did you implement:

Current constraint T: Item on the blanket impl is too restrictive, this PR relaxes that

How did you verify your change:

via CI

What (if anything) would need to be called out in the CHANGELOG for the next release:

  • Attribute is now implemented for any type that implements FromAttributes + IntoAttributes instead of Item
+520 -202

0 comment

12 changed files

pr created time in 13 days

create barnchVeetaha/dynomite

branch : feat/impl-attr-for-into-from-attrs

created branch time in 13 days

create barnchVeetaha/dynomite

branch : feat/fat-enums

created branch time in 13 days

pull request commentsoftprops/dynomite

Introduce #[dynomite(flatten)] attribute

I disabled trybuild test on beta and nightly, but they still run on stable

Veetaha

comment created time in 13 days

push eventVeetaha/dynomite

Veetaha

commit sha ba4d54a562fdda24202bfedd92d7db3405becddf

Execute trybuild tests only on stable See the comment for the reasoning

view details

push time in 13 days

pull request commentsoftprops/dynomite

Introduce #[dynomite(flatten)] attribute

Nightly job started failing because of the update error message, so I made unstable versions into optional jobs (a9022b3): https://github.com/rust-lang/rust/pull/76406

Veetaha

comment created time in 13 days

push eventVeetaha/dynomite

Veetaha

commit sha a9022b399328bc0eb2e7676fe44821790cbff2ae

Make unstable toolchain versions jobs optional to pass The first instance of the need for this is try-build tets: Nightly `rustc ` has updated its error message and this causes nightly job to fail now

view details

push time in 13 days

push eventVeetaha/dynomite

Veetaha

commit sha 08ef507923ff86f7e6a94c3c7c0e6c27f3c16569

cargo fmt

view details

push time in 13 days

Pull request review commentsoftprops/dynomite

Introduce #[dynomite(flatten)] attribute

 struct ItemField<'a> { impl<'a> ItemField<'a> {     fn new(field: &'a Field) -> Self {         let attrs = parse_attrs(&field.attrs);-        Self { field, attrs }+        let me = Self { field, attrs };+        if me.is_flatten() {+            if let Some(it) = me

I've added more docs for the attributes to the crate level of dynomite (this is basically the entrypoint for our API discovery). See commit 5e36924.

I'd like to merge this without too many more additions not to bloat this PR, I am inclined to make a cleanup in a separate PR. As you've mentioned it is better to do atomic PRs with targeted changes

Veetaha

comment created time in 13 days

PullRequestReviewEvent

push eventVeetaha/dynomite

Veetaha

commit sha 5e36924832e7b06bcf76244d45172e97e323fc5a

Better document dynomite attributes

view details

push time in 13 days

Pull request review commentsoftprops/dynomite

Introduce #[dynomite(flatten)] attribute

 //!   user: Uuid, //!   #[dynomite(sort_key)] //!   order_id: Uuid,-//!   color: Option<String>+//!   color: Option<String>,+//! }+//!+//! #[derive(Item)]+//! struct ShoppingCart {+//!     #[dynomite(partition_key)]+//!     id: Uuid,+//!     // A separate struct to store data without any id+//!     #[dynomite(flatten)]

Flattening is required to support flat fat enums:

#[derive(Item)] 
struct MyItem {
    #[dynomite(partition_key)]
    id: String,
    #[dynomite(flatten)]
    my_enum: Foo,
}

#[dynomite(tag = "kind")]
enum Foo {
    Bar(Bar),
}

#[derive(Attributes)]
struct Bar {
    bar: u32
}

Without that flatten attribute the item would be serialized as:

{
    "id": "1234",
    "my_enum": {
         "kind": "Bar", // can't use neither kind, nor bar as a sort key or GSI primary key
         "bar": 42,
    }
}

which won't work if you want to make bar or kind fields a partition or sort key. With flatten this becomes possible:

{
     "id": "1234"
     "kind": "Bar",
     "bar": 42,
}

I've started with flatten, so I can't give an example with a fat enum right now in this PR. Otherwise flatten is useful to extract repetitive data, maybe even construct the items itself from disjoint projections, or just have the id-less struct that contains only datums (this is useful when id is not yet known):

#[derive(Item)]
struct User {
    #[dynomite(partition_key)]
    id: Uuid,
    #[dynomite(flatten)]
    profile: UserProfile,
}

#[derive(Attributes)]
struct UserProfile {
    name: String,
    avatar: Url,
}

// Accepts data, no id field is required to be filled by the caller
async fn create_user(data: UserProfile) -> Result<User> {
     let user = User {
          id: Uuid::new_v4(),
          profile: data,
     };
     db.write_item({ user.clone()... }).await?;
     user
}

Though for the last point we may just add yet another proc macro to generate struct without the partition key field and update changeset structs with all fields as Option<T>.

In this example here I have shown extracting the data from id into a separate struct because I cannot show an example with a flat fat enum yet...

Veetaha

comment created time in 13 days

Pull request review commentsoftprops/dynomite

Introduce #[dynomite(flatten)] attribute

 pub trait Attribute: Sized {     fn from_attr(value: AttributeValue) -> Result<Self, AttributeError>; } +impl Attribute for AttributeValue {

Sure, this particular impl Attribute for AttributeValue is required to make this work:

#[derive(Attributes)]
struct Foo {
    bar: u32,
    #[dynomite(flatten)]
    remaining: Attributes,
}
Veetaha

comment created time in 14 days

Pull request review commentsoftprops/dynomite

Introduce #[dynomite(flatten)] attribute

 pub trait Attribute: Sized {     fn from_attr(value: AttributeValue) -> Result<Self, AttributeError>; } +impl Attribute for AttributeValue {+    fn into_attr(self: Self) -> AttributeValue {+        self+    }+    fn from_attr(value: AttributeValue) -> Result<Self, AttributeError> {+        Ok(value)+    }+}+ /// A type capable of being produced from /// a set of string keys and `AttributeValues` pub trait FromAttributes: Sized {+    /// Shortcut for `FromAttributes::from_mut_attrs(&mut attrs)`.+    /// You should generally implement only that method.+    fn from_attrs(mut attrs: Attributes) -> Result<Self, AttributeError> {+        Self::from_mut_attrs(&mut attrs)+    }+     /// Returns an instance of of a type resolved at runtime from a collection-    /// of a `String` keys and `AttributeValues`. If-    /// a instance can not be resolved and `AttributeError` will be returned.-    fn from_attrs(attrs: Attributes) -> Result<Self, AttributeError>;+    /// of a `String` keys and `AttributeValues`.+    /// If an instance can not be resolved and `AttributeError` will be returned.+    /// The implementations of this method should remove the relevant key-value+    /// pairs from the map to consume them. This is needed to support

These methods are not both mut. from_attrs consumes the input and it is just the argument variable itself which is mutable, the implementors of this method are not required to make it mut too. This is the same as the difference between Vec::drain(&mut self) and Vec::into_iter([mut] self), the mutability of self on into_iter doesn't matter. Do you want to remove the consuming method and instead just have fn from_attrs(&mut Attributes) ?

Veetaha

comment created time in 14 days

Pull request review commentsoftprops/dynomite

Introduce #[dynomite(flatten)] attribute

 pub trait Attribute: Sized {     fn from_attr(value: AttributeValue) -> Result<Self, AttributeError>; } +impl Attribute for AttributeValue {+    fn into_attr(self: Self) -> AttributeValue {+        self+    }+    fn from_attr(value: AttributeValue) -> Result<Self, AttributeError> {+        Ok(value)+    }+}+ /// A type capable of being produced from /// a set of string keys and `AttributeValues` pub trait FromAttributes: Sized {+    /// Shortcut for `FromAttributes::from_mut_attrs(&mut attrs)`.+    /// You should generally implement only that method.+    fn from_attrs(mut attrs: Attributes) -> Result<Self, AttributeError> {+        Self::from_mut_attrs(&mut attrs)+    }+     /// Returns an instance of of a type resolved at runtime from a collection-    /// of a `String` keys and `AttributeValues`. If-    /// a instance can not be resolved and `AttributeError` will be returned.-    fn from_attrs(attrs: Attributes) -> Result<Self, AttributeError>;+    /// of a `String` keys and `AttributeValues`.+    /// If an instance can not be resolved and `AttributeError` will be returned.+    /// The implementations of this method should remove the relevant key-value+    /// pairs from the map to consume them. This is needed to support+    /// `#[dynomite(flatten)]` without creating temporary hash maps.+    fn from_mut_attrs(attrs: &mut Attributes) -> Result<Self, AttributeError>; }  /// Coerces a homogenious HashMap of attribute values into a homogeneous Map of types /// that implement Attribute #[allow(clippy::implicit_hasher)] impl<A: Attribute> FromAttributes for HashMap<String, A> {-    fn from_attrs(attrs: Attributes) -> Result<Self, AttributeError> {+    fn from_mut_attrs(attrs: &mut Attributes) -> Result<Self, AttributeError> {         attrs-            .into_iter()-            .try_fold(HashMap::new(), |mut result, (k, v)| {-                result.insert(k, A::from_attr(v)?);-                Ok(result)-            })+            .drain()+            .map(|(k, v)| Ok((k, A::from_attr(v)?)))+            .collect()     } }  /// Coerces a homogenious Map of attribute values into a homogeneous BTreeMap of types /// that implement Attribute impl<A: Attribute> FromAttributes for BTreeMap<String, A> {-    fn from_attrs(attrs: Attributes) -> Result<Self, AttributeError> {+    fn from_mut_attrs(attrs: &mut Attributes) -> Result<Self, AttributeError> {         attrs-            .into_iter()-            .try_fold(BTreeMap::new(), |mut result, (k, v)| {-                result.insert(k, A::from_attr(v)?);-                Ok(result)-            })+            .drain()+            .map(|(k, v)| Ok((k, A::from_attr(v)?)))+            .collect()+    }+}++/// You should implement this trait instead of `From<T> for Attributes`+/// for your type to support flattening, `#[dynomite(Attributes/Item)]` will+/// generate both the implementation of this trait and `From<T>`+/// (there is no blanket impl for `From<T>` here due to orphan rules)

This trait is needed for HashMap<String, Attributes> to work because we don't #[derive(Attributes)] for this type. We could also make this reminiscent of Attribute trait:

// New name for `Attributes` type alias we have right now
type AttrMap = HashMap<String, AttributeValue>;
trait Attributes {
     fn from_attrs(&mut Attributes) -> Result<Self>;
     fn into_attrs(self, &mut Attributes);
}

but since we already have FromAttributes I thought it's better not to add IntoAttributes rather than changing trait FromAttributes -> trait Attributes as above

Veetaha

comment created time in 13 days

PullRequestReviewEvent
PullRequestReviewEvent
PullRequestReviewEvent

Pull request review commentsoftprops/dynomite

Introduce #[dynomite(flatten)] attribute

 pub type Attributes = HashMap<String, AttributeValue>; /// } /// /// impl FromAttributes for Person {-///     fn from_attrs(attrs: Attributes) -> Result<Self, AttributeError> {+///     fn from_mut_attrs(attrs: &mut Attributes) -> Result<Self, AttributeError> { ///         Ok(Self { ///             id: attrs-///                 .get("id")-///                 .and_then(|val| val.s.clone())-///                 .ok_or(AttributeError::MissingField { name: "id".into() })?,+///                 .remove("id")+///                 .and_then(|val| val.s)+///                 .ok_or_else(|| AttributeError::MissingField { name: "id".into() })?, ///         }) ///     } /// } ///-/// impl Into<Attributes> for Person {-///     fn into(self: Self) -> Attributes {-///         let mut attrs = HashMap::new();+/// impl IntoAttributes for Person {+///     fn into_mut_attrs(+///         self,+///         attrs: &mut Attributes,+///     ) { ///         attrs.insert("id".into(), "123".to_string().into_attr());-///         attrs ///     } /// }+///+/// // Unfortunately `dynomite` is not able to provide a blanket impl for this trait

This is an example of not using derive attributes and making a manual impl:

Below is an example of doing this manually for demonstration.

Veetaha

comment created time in 14 days

pull request commentsoftprops/dynomite

Introduce #[dynomite(flatten)] attribute

@softprops the switch from consuming the attributes from_attrs(HashMap<String, AttributeValue>) to taking by a mut reference: from_mut_attrs(&mut HashMap<String, AttributeValue>) is required for both easier implementation and performance.

The process of deserializing would otherwise need to clone and find the difference between the hashmaps for each flatten attribute:

use dynomite::{Attributes, FromAttributes, Attribute};

#[derive(Attributes)]
struct Foo {
    a: u32,
    #[derive(flatten)]
    flat: Bar,
    #[derive(flatten)]
    remainder: Attributes,
}

#[derive(Attributes)]
struct Bar {
    b: bool,
}

// This code would be generated
impl FromAttributes for Foo {
    fn from_attrs(mut attrs: Attributes) -> Result<Self, dynomite::AttributeError> {
        let a: u32 = Attribute::from_attr(attrs.remove("a"))?;
        let flat: Bar = FromAttributes::from_attrs(attrs.clone())?;
        while let Some(_) = attrs.remove() {}
        Foo {
            a,
            flat,
            remainder: attrs,
        }
    }
}

// Instead this is generated:
impl FromAttributes for Foo {
    fn from_mut_attrs(attrs: &mut Attributes) -> Result<Self, dynomite::AttributeError> {
        let a: u32 = Attribute::from_attr(attrs.remove("a"))?;
        let flat: Bar = FromAttributes::from_attrs(attrs)?;
        let remainder = attrs.drain().collect();
        Foo {
            a,
            flat,
            remainder: attrs.,
        }
    }
}
Veetaha

comment created time in 14 days

issue openedsoftprops/dynomite

Validate attrobites key names at compile time

<!-- Please search existing issues to avoid creating duplicates. -->

💡 Feature description

Dynamodb has rules for naming the attributes keys defined here. It also includes quite a long list of arguably common words as reserved names (which I think are unjustifiably common, but anyway...).

💻 Basic example

#[derive(Attributes)]
struct MyTable {
     // Nope, column is a reserved word, `dynomite` issues a compile-error here,
     // This should also work with `rename = "foo"`
     column: String,
}

created time in 14 days

pull request commentsoftprops/dynomite

Introduce #[dynomite(flatten)] attribute

I recommend not releasing this one when it is merged to master. I am working on support for fat enums and it will have yet one more breaking change...

Veetaha

comment created time in 14 days

pull request commentsoftprops/dynomite

Introduce #[dynomite(flatten)] attribute

cc @softprops

Veetaha

comment created time in 14 days

issue commentborntyping/rust-simple_logger

Ability to select logging to stderr

@piegamesde thank you for the involvement. This does require some internal mutability, and I assure you neither RefCell nor Mutex are a bad thing, it's important to evaluate the options, and you've already shown some of them.

I recommend taking a look at println! internals. At first glance it uses some thread_local! RefCell<Option<Box<dyn Write + Send>>>, but it is initialized with None and I guess is never overwritten, because it is exposed only via an unstable function set_print. So it ignores this thread-lockal value in print_to and does use a global stdout lock with a ReentrantMutex by calling std::io::stdout() function. Inside of its io::Write impl Stdout locks this reentrant mutex on each write.

So, in conclusion, I'll say that Mutex/ReentrantMutex is not a bad thing, I don't see other means of sharing a global mutable io stream. We might try to copy the setup used in stdout, maybe use an enum like this to support already Sync types:

struct ConcurrentWriter {
     Unsync(ReentrantMutex<Box<dyn Write + Send>>),
     Sync(Box<dyn Write + Send + Sync>)
}

though I see this is going to be quite complicated for a simple_logger. Taking this into account, I think, it does make sense just to add a fixed switch between stdout/stderr via a boolean setter on the builder, or via a conditional compilation (cargo feature like features = ["stderr"]), though I'd just go with a boolean setter.

Veetaha

comment created time in 15 days

push eventVeetaha/dynomite

Veetaha

commit sha 49955e3c3465aa7564be14fc8b36543feb83e988

More cleanup

view details

push time in 15 days

push eventVeetaha/dynomite

Veetaha

commit sha d9e4108c04a9a94003f2b04259728703d165a4cb

Impl Attribute for AttributeValue itself

view details

push time in 15 days

push eventVeetaha/dynomite

Veetaha

commit sha b266e48b10c692754bb7fe1132d9d85ced5c8648

Cleanup

view details

push time in 15 days

push eventVeetaha/dynomite

Veetaha

commit sha d87ca1ace4eb0a34a6d4b84d1f09a54638fd4e5a

Fix typo

view details

push time in 15 days

push eventVeetaha/dynomite

Veetaha

commit sha 33d67f846bed7787eccf5d8f9b4f8179234f7015

Rename *_sink -> *_mut_attrs This naming seems to better fit Rust API guidelines: https://github.com/softprops/dynomite/pull/132#issuecomment-688956680

view details

push time in 15 days

pull request commentsoftprops/dynomite

Introduce #[dynomite(flatten)] attribute

I am still hesitating about naming:

from_mut_attrs(&mut Atttributes) / from_attrs_sink(&mut Attributes)
into_mut_attrs(self, &mut Attributes) / into_attrs_sink(self, &mut Attributes)

Wdyt?

Veetaha

comment created time in 15 days

push eventVeetaha/dynomite

Veetaha

commit sha 91d8297e5deb9ff32040151cdac5af713103f93b

Small cleanup

view details

push time in 15 days

pull request commentsoftprops/dynomite

Introduce #[dynomite(flatten)] attribute

Added traits to make flattening work more naturally (and support collecting additional attributes as told here: https://github.com/softprops/dynomite/pull/132#discussion_r484928983). This should be ready to merge. cc @anelson

Veetaha

comment created time in 15 days

push eventVeetaha/dynomite

Veetaha

commit sha c7468ed4ec7dc52db5f5fc9c40d7b235b80dc71c

Introduce IntoAttributes trait and from_attrs_sink method This also adds support for collecting all additional properties into a hash map. **BREAKING CHANGE**: Now the users have to implement `from_attrs_sink(&mut Attributes)` instead of `from_attrs() -> Attributes` The existing `from_attrs()` method has a default implementation.

view details

push time in 15 days

Pull request review commentsoftprops/dynomite

Introduce #[dynomite(flatten)] attribute

 use syn::{ };  #[derive(Clone)]-pub enum Attr {+pub(crate) struct Attr {

The motivation is to extract the ident into a separate field so that accessing it was trivial instead of doing a match:

let ident = match attr {
    Attr::Default(it) => it,
    Attr::Rename(it, _) => it,
    Attr::PartitionKey(it) => it,
    // ...
};
Veetaha

comment created time in 15 days

PullRequestReviewEvent

Pull request review commentsoftprops/dynomite

Introduce #[dynomite(flatten)] attribute

+error: If #[dynomite(flatten)] is used, no other dynomite attributes are allowed on the field+ --> $DIR/default-with-flatten.rs:5:16+  |+5 |     #[dynomite(default, flatten)]

This needs more design effort, I am not sure I'll be able to add support for (default, flatten) in this PR.

The PR is a draft, I want to propagate those generated #[doc(hidden)] methods to a FromAttributes trait to support flattening on HashMap<String, T: Attribute> to be able to collect all the remaining fields of the object (as it is in serde)

Veetaha

comment created time in 15 days

PullRequestReviewEvent

push eventVeetaha/dynomite

Veetaha

commit sha 42df9240ff7605f9523ea812198837c3d27bb413

cargo fmt

view details

push time in 15 days

push eventVeetaha/dynomite

Veetaha

commit sha 22534b09efcfae2854aa4cd76bc261e9b42a8cb1

cargo fmt

view details

push time in 15 days

PR opened softprops/dynomite

Introduce #[dynomite(flatten)] attribute

What did you implement:

This works like #[serde(flatten)], the fields of the nested struct are flattened to the attributes of the surrounding struct where the flattened field is declared. The reverse mapping is done when parsing the struct from raw Attributes.

How did you verify your change:

Added a unit test, compile_fail test, and a documentation (doc test)

What (if anything) would need to be called out in the CHANGELOG for the next release:

  • Introduce #[dynomite(flatten)] field attribute
+204 -70

0 comment

6 changed files

pr created time in 16 days

push eventVeetaha/dynomite

Veetaha

commit sha 1339dfd4d942a3f9d2a08b449d87a704a5103bf2

Add more docs on the flatten field

view details

push time in 16 days

push eventVeetaha/dynomite

Veetaha

commit sha 5c3c7dae149311d3bcb88e1d4d5c1deff6c1039d

Introduce #[dynomite(flatten)] attribute

view details

Veetaha

commit sha dabdccc35455a6eb7da66409fbf6d8466b3e85c6

Add more docs on the flatten field

view details

push time in 16 days

create barnchVeetaha/dynomite

branch : feat/flatten

created branch time in 16 days

more