Files
GitJournal/lib/storage/git_storage.dart
Vishesh Handa 186f6b0af3 Refactor: Remove FileStorage
With this, the application compiles again. And note editing is working
again. This is was the first of some small refactors in order to
implement both async note loading and a support for directories.
2019-09-26 17:22:52 +02:00

112 lines
2.9 KiB
Dart

import 'dart:async';
import 'dart:io';
import 'package:fimber/fimber.dart';
import 'package:flutter/foundation.dart';
import 'package:journal/apis/git.dart';
import 'package:journal/note.dart';
import 'package:journal/settings.dart';
import 'package:journal/storage/notes_repository.dart';
import 'package:path/path.dart' as p;
class GitNoteRepository implements NoteRepository {
final String dirName;
final String subDirName;
final String baseDirectory;
String notesBasePath;
final GitRepo _gitRepo;
bool cloned = false;
bool checkForCloned = false;
// vHanda: This no longer needs to be so complex. It will only ever take the baseDirectory + dirName
// The directory should already exist!
GitNoteRepository({
@required this.dirName,
@required this.subDirName,
@required this.baseDirectory,
}) : _gitRepo = GitRepo(
folderName: dirName,
authorEmail: Settings.instance.gitAuthorEmail,
authorName: Settings.instance.gitAuthor,
) {
notesBasePath = p.join(baseDirectory, dirName, subDirName);
}
@override
Future<NoteRepoResult> addNote(Note note) async {
return _addNote(note, "Added Journal Entry");
}
Future<NoteRepoResult> _addNote(Note note, String commitMessage) async {
await note.save();
await _gitRepo.add(".");
await _gitRepo.commit(
message: commitMessage,
);
return NoteRepoResult(noteFilePath: note.filePath, error: false);
}
@override
Future<NoteRepoResult> removeNote(Note note) async {
var gitDir = p.join(baseDirectory, dirName);
var pathSpec = note.filePath.replaceFirst(gitDir, "").substring(1);
// We are not calling note.remove() as gitRm will also remove the file
await _gitRepo.rm(pathSpec);
await _gitRepo.commit(
message: "Removed Journal entry",
);
return NoteRepoResult(noteFilePath: note.filePath, error: false);
}
Future<NoteRepoResult> resetLastCommit() async {
await _gitRepo.resetLast();
return NoteRepoResult(error: false);
}
@override
Future<NoteRepoResult> updateNote(Note note) async {
return _addNote(note, "Edited Journal Entry");
}
@override
Future<List<Note>> listNotes() async {
final dir = Directory(notesBasePath);
var notes = <Note>[];
var lister = dir.list(recursive: false);
await for (var fileEntity in lister) {
var note = Note(filePath: fileEntity.path);
if (!note.filePath.toLowerCase().endsWith('.md')) {
continue;
}
notes.add(note);
}
// Reverse sort
notes.sort((a, b) => b.compareTo(a));
return notes;
}
@override
Future<bool> sync() async {
try {
await _gitRepo.pull();
} on GitException catch (ex) {
Fimber.d(ex.toString());
}
try {
await _gitRepo.push();
} on GitException catch (ex) {
Fimber.d(ex.toString());
rethrow;
}
return true;
}
}