dart-lang / pubspec_parse

Simple package for parsing pubspec.yaml files with a type-safe API and rich error reporting
https://pub.dev/packages/pubspec_parse
BSD 3-Clause "New" or "Revised" License
53 stars 25 forks source link

Provide an example? #115

Closed lsgd closed 4 months ago

lsgd commented 1 year ago

I'm having a hard time to parse the pubspec.yaml, mainly I can't access the content of my pubspec.yaml

If I try to simply read it with File(), I get the following error:

final pubspec = await File('pubspec.yaml').readAsString();

Exception has occurred.
PathNotFoundException (PathNotFoundException: Cannot open file, path = 'pubspec.yaml' (OS Error: No such file or directory, errno = 2))

If I use rootBundle, I get another error:

final pubspec = rootBundle.loadString(
      "packages/<my_package_name>/pubspec.yaml",
    );

FlutterError (Unable to load asset: "packages/<my_package_name>/pubspec.yaml".
The asset does not exist or has empty data.)

I replaced <my_package_name> with the name specified in pubspec.yaml, as well as with the package attribute value <manifest [...] package="tld.mydomain.myapp"> from the AndroidManifest.xml. Both times it failed.


My code looks the following:

import 'package:pubspec_parse/pubspec_parse.dart';

[...]

  Future<String> getVersion() async {
    final pubspec = await File('pubspec.yaml').readAsString();
    final parsed = Pubspec.parse(pubspec);
    return parsed.version == null ? '?' : parsed.version!.canonicalizedVersion;
  }

and my file structure looks like this

./pubspec.yaml
./lib/src/screens/imprint.dart     // <-- contains function getVersion()

I haven't modified anything else, like I didn't add "pubspec.yaml" to assets in pubspec.yaml or similar. But even if I add "pubspec.yaml", the code fails with the PathNotFoundException error. Do I miss something?

It would be really helpful if the README would contain a working example to showcase how to use this module. Thanks a lot.

kevmoo commented 4 months ago

The pubspec for your project DOES NOT exist in the compiled Flutter application. This package is meant to be used in tools.

maheshj01 commented 4 months ago

@kevmoo Is there a way to read the dependencies or pubspec.yaml content in flutter applications?

kevmoo commented 4 months ago

@maheshmnj not unless you package the pubspec somehow in the build process. It's like asking if you can read the source code of a Dart file in a flutter application. It's just not there (unless you do work) after the app is built and deployed.