Visitar URL original
Adds xdg_directories package to access Linux well known directories. by gspencergoog · Pull Request #117 · flutter/packages · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Switch to separate calls to get user dirs.
  • Loading branch information
gspencergoog committed Mar 5, 2020
commit 4db58d3b3d6b5ef9a78e1647fa92ddb7b22f9f0a
58 changes: 39 additions & 19 deletions packages/xdg_directories/lib/xdg_directories.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
// Copyright 2020 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

library xdg_directories;

import 'dart:convert';
Expand All @@ -7,13 +11,34 @@ import 'package:flutter/cupertino.dart';
import 'package:path/path.dart' as path;
import 'package:process/process.dart';

/// An override function used by the tests to override the environment variable
/// lookups using [xdgEnvironmentOverride].
typedef EnvironmentOverride = String Function(String envVar);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems odd to call the type Override when it's used for the real implementation too. EnviromentGetter?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, good point. I went with EnvironmentAccessor.


/// A testing setter that replaces the real environment lookups with an override.
///
/// Set to null to stop overriding.
///
/// Only available to tests.
@visibleForTesting
set xdgEnvironmentOverride(EnvironmentOverride override) => _getenv = override ?? _productionGetEnv;
set xdgEnvironmentOverride(EnvironmentOverride override) {
_xdgEnvironmentOverride = override;
_getenv = _xdgEnvironmentOverride ?? _productionGetEnv;
}

/// A testing getter that returns the current value of the override that
/// replaces the real environment lookups with an override.
///
/// Only available to tests.
EnvironmentOverride get xdgEnvironmentOverride => _xdgEnvironmentOverride;
EnvironmentOverride _xdgEnvironmentOverride;
EnvironmentOverride _productionGetEnv = (String value) => Platform.environment[value];
EnvironmentOverride _getenv = _productionGetEnv;

/// A testing function that replaces the process manager used to run xdg-user-path
/// with the one supplied.
///
/// Only available to tests.
@visibleForTesting
set xdgProcessManager(ProcessManager processManager) {
_processManager = processManager;
Expand Down Expand Up @@ -97,47 +122,42 @@ Directory get dataHome => _directoryFromEnvironment('XDG_DATA_HOME', '.local/sha
/// Throws [StateError] if the HOME environment variable is not set.
Directory get runtimeDir => _directoryFromEnvironment('XDG_RUNTIME_DIR', null);

Directory _getUserDir(String dirName) {
/// Gets the xdg user directory named by `dirName`.
///
/// Use [getUserDirectoryNames] to find out the list of available names.
Directory getUserDirectory(String dirName) {
final ProcessResult result = _processManager.runSync(
<String>['xdg-user-dir', dirName],
// Copy these env vars from the override so that the tests can override them.
environment: <String, String>{
'HOME': _getenv('HOME'),
'XDG_CONFIG_HOME': _getenv('XDG_CONFIG_HOME'),
},
includeParentEnvironment: true,
stdoutEncoding: Encoding.getByName('utf8'),
);
final String path = utf8.decode(result.stdout).split('\n')[0];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

trim() before split, just in case an implementation adds an extra newline before the actual output?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm going to keep what I have: I don't want to remove any leading/trailing whitespace that might be part of the path, as unlikely as that is.

return Directory(path);
}

/// The list of user directories defined in the `xdg`
/// configuration files.
/// Gets the set of user directory names that xdg knows about.
///
/// Reads the file [configHome]`/user-dirs.dirs` to get the information from it.
/// These are not paths, they are names of xdg values. Call [getUserDirectory]
/// to get the associated directory.
///
/// The map keys are the name of the configuration variable, with `XDG_`
/// stripped from the beginning of the name, and `_DIR` stripped from the
/// end. They are typically uppercase.
///
/// Throws [StateError] if the HOME environment variable is not set.
Map<String, Directory> getUserDirs() {
/// These are the names of the variables in "[configHome]/user-dirs.dirs", with
/// the `XDG_` prefix removed and the `_DIR` suffix removed.
Set<String> getUserDirectoryNames() {
final File configFile = File(path.join(configHome.path, 'user-dirs.dirs'));
List<String> contents;
try {
contents = configFile.readAsLinesSync();
} on FileSystemException catch (e) {
return const <String, Directory>{};
return const <String>{};
}
final Map<String, Directory> result = <String, Directory>{};
final Set<String> result = <String>{};
final RegExp dirRegExp = RegExp(r'^\s*XDG_(?<dirname>.*)_DIR\s*=\s*(?<dir>.*)\s*$');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/./[^=]/ maybe? Theoretically, although extremely unlikely, _DIR= could be part of a path value.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point, thanks. Added.

for (String line in contents) {
final RegExpMatch match = dirRegExp.firstMatch(line);
if (match == null) {
continue;
}
result[match.namedGroup('dirname')] = _getUserDir(match.namedGroup('dirname'));
result.add(match.namedGroup('dirname'));
}
return result;
}
2 changes: 1 addition & 1 deletion packages/xdg_directories/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ dependencies:
sdk: flutter

dev_dependencies:
# mockito: ">=4.1.1"
mockito: ">=4.1.1"
flutter_test:
sdk: flutter

Expand Down
40 changes: 35 additions & 5 deletions packages/xdg_directories/test/xdg_directories_test.dart
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
// Copyright 2020 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:convert';
import 'dart:io';

import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as path;
import 'package:mockito/mockito.dart' show Fake;
import 'package:process/process.dart';

import 'package:xdg_directories/xdg_directories.dart' as xdg;

Expand Down Expand Up @@ -41,11 +45,14 @@ XDG_VIDEOS_DIR="$HOME/Videos"
if (tmpDir != null) {
tmpDir.deleteSync(recursive: true);
}
// Stop overriding the environment accessor.
xdg.xdgEnvironmentOverride = null;
});
void expectDirList(List<Directory> values, List<String> expected) {
final List<String> valueStr = values.map<String>((Directory directory) => directory.path).toList();
expect(valueStr, orderedEquals(expected));
}

test('Default fallback values work', () {
fakeEnv.clear();
fakeEnv['HOME'] = tmpDir.path;
Expand Down Expand Up @@ -80,14 +87,37 @@ XDG_VIDEOS_DIR="$HOME/Videos"
'TEMPLATES': path.join(tmpDir.path, 'Templates'),
'VIDEOS': path.join(tmpDir.path, 'Videos'),
};
final Map<String, Directory> userDirs = xdg.getUserDirs();
expect(userDirs.keys.toSet(), equals(expected.keys.toSet()));
for (String key in userDirs.keys) {
expect(userDirs[key].path, equals(expected[key]), reason: 'Path $key value not correct');
xdg.xdgProcessManager = FakeProcessManager(expected);
final Set<String> userDirs = xdg.getUserDirectoryNames();
expect(userDirs, equals(expected.keys.toSet()));
for (String key in userDirs) {
expect(xdg.getUserDirectory(key).path, equals(expected[key]), reason: 'Path $key value not correct');
}
xdg.xdgProcessManager = const LocalProcessManager();
});
test('Throws StateError when HOME not set', () {
fakeEnv.clear();
expect(() { xdg.configHome; }, throwsStateError);
expect(() {
xdg.configHome;
}, throwsStateError);
});
}

class FakeProcessManager extends Fake implements ProcessManager {
FakeProcessManager(this.expected);

Map<String, String> expected;

@override
ProcessResult runSync(
List<dynamic> command, {
String workingDirectory,
Map<String, String> environment,
bool includeParentEnvironment: true,
bool runInShell: false,
Encoding stdoutEncoding: systemEncoding,
Encoding stderrEncoding: systemEncoding,
}) {
return ProcessResult(0, 0, expected[command[1]].codeUnits, <int>[]);
}
}