├── .gitignore ├── deno.json ├── .nova └── Configuration.json ├── src ├── util.ts ├── main.ts ├── upgrade.ts ├── servers.ts ├── identity.ts └── share.ts ├── deps.ts ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | data 2 | test-fs-sync -------------------------------------------------------------------------------- /deno.json: -------------------------------------------------------------------------------- 1 | { 2 | "tasks": { 3 | "cli": "deno run --unstable --allow-all --no-check src/main.ts" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /.nova/Configuration.json: -------------------------------------------------------------------------------- 1 | { 2 | "co.gwil.deno.config.enableLinting" : "true", 3 | "co.gwil.deno.config.enableLsp" : "true", 4 | "co.gwil.deno.config.enableUnstable" : "true", 5 | "co.gwil.deno.config.formatOnSave" : "null", 6 | "workspace.art_style" : 0, 7 | "workspace.name" : "earthstar-cli" 8 | } 9 | -------------------------------------------------------------------------------- /src/util.ts: -------------------------------------------------------------------------------- 1 | export function logWarning(msg: string) { 2 | console.error(`%c${msg}`, "color: red"); 3 | } 4 | 5 | export function logSuccess(msg: string) { 6 | console.error(`%c${msg}`, "color: green"); 7 | } 8 | 9 | export function logEmphasis(msg: string) { 10 | console.error(`%c${msg}`, "color: blue"); 11 | } 12 | -------------------------------------------------------------------------------- /deps.ts: -------------------------------------------------------------------------------- 1 | export * as Earthstar from "https://deno.land/x/earthstar@v9.3.3/mod.ts"; 2 | export * as Cliffy from "https://deno.land/x/cliffy@v0.25.4/mod.ts"; 3 | export { keypress } from "https://deno.land/x/cliffy@v0.22.2/keypress/mod.ts"; 4 | export { default as distanceToNow } from "https://deno.land/x/date_fns@v2.9.0/formatDistanceToNow/index.js"; 5 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { Cliffy } from "../deps.ts"; 2 | 3 | import { registerIdentityCommand } from "./identity.ts"; 4 | import { registerServerCommands } from "./servers.ts"; 5 | import { registerShareCommands } from "./share.ts"; 6 | import { registerUpgradeCommand } from "./upgrade.ts"; 7 | 8 | const mainCommand = new Cliffy.Command() 9 | .name("earthstar") 10 | .version("v8.3.5").description( 11 | "Sync, view, and write documents to Earthstar shares.", 12 | ).action(() => { 13 | mainCommand.showHelp(); 14 | }); 15 | 16 | registerIdentityCommand(mainCommand); 17 | registerShareCommands(mainCommand); 18 | registerServerCommands(mainCommand); 19 | registerUpgradeCommand(mainCommand); 20 | 21 | mainCommand.command("completions", new Cliffy.CompletionsCommand()); 22 | 23 | await mainCommand.parse(Deno.args); 24 | -------------------------------------------------------------------------------- /src/upgrade.ts: -------------------------------------------------------------------------------- 1 | import { Cliffy } from "../deps.ts"; 2 | 3 | export function registerUpgradeCommand(cmd: Cliffy.Command) { 4 | const currentVersion = cmd.getVersion(); 5 | 6 | cmd.command( 7 | "upgrade", 8 | new Cliffy.Command().description( 9 | "Upgrade the Earthstar CLI to the latest version.", 10 | ).option("--version ", "The version to install").action( 11 | async ({ version }) => { 12 | const { latest, versions } = await getVersions(); 13 | 14 | if (currentVersion === latest && !version) { 15 | console.log("You have the latest version of the Earthstar CLI."); 16 | Deno.exit(0); 17 | } 18 | 19 | if (version && !versions.includes(version)) { 20 | console.log(`The requested version (${version}) was not found.`); 21 | Deno.exit(1); 22 | } 23 | 24 | const process = Deno.run({ 25 | cmd: [ 26 | Deno.execPath(), 27 | "install", 28 | "--allow-read", 29 | "--allow-write", 30 | "--allow-net", 31 | "--allow-run", 32 | "--allow-env", 33 | "--no-check", 34 | "--unstable", 35 | "-f", 36 | "--location", 37 | "https://earthstar-project.org", 38 | "-n", 39 | "earthstar", 40 | `https://deno.land/x/earthstar_cli@${ 41 | version ? version : latest 42 | }/src/main.ts`, 43 | ], 44 | }); 45 | await process.status(); 46 | }, 47 | ), 48 | ); 49 | } 50 | 51 | export async function getVersions(): Promise< 52 | { latest: string; versions: string[] } 53 | > { 54 | const aborter = new AbortController(); 55 | const timer = setTimeout(() => aborter.abort(), 2500); 56 | const response = await fetch( 57 | "https://cdn.deno.land/earthstar_cli/meta/versions.json", 58 | { signal: aborter.signal }, 59 | ); 60 | if (!response.ok) { 61 | throw new Error( 62 | "couldn't fetch the latest version - try again after sometime", 63 | ); 64 | } 65 | const data = await response.json(); 66 | clearTimeout(timer); 67 | return data; 68 | } 69 | -------------------------------------------------------------------------------- /src/servers.ts: -------------------------------------------------------------------------------- 1 | import { Cliffy } from "../deps.ts"; 2 | import { logSuccess, logWarning } from "./util.ts"; 3 | 4 | const LS_SERVERS_KEY = "servers"; 5 | 6 | export function getServers(): string[] { 7 | const result = localStorage.getItem(LS_SERVERS_KEY); 8 | return result ? JSON.parse(result) : []; 9 | } 10 | 11 | function setServers(servers: string[]): void { 12 | localStorage.setItem(LS_SERVERS_KEY, JSON.stringify(servers)); 13 | } 14 | 15 | function addServer(server: string) { 16 | const url = new URL(server); 17 | 18 | const servers = getServers(); 19 | 20 | if (servers.includes(url.toString())) { 21 | throw new Error(`Already know about ${server}`); 22 | } 23 | 24 | const next = [...servers, url.toString()]; 25 | 26 | setServers(next); 27 | } 28 | 29 | function removeServer(address: string): boolean { 30 | const servers = getServers(); 31 | 32 | const nextServers = servers.filter((server) => server !== address); 33 | 34 | setServers(nextServers); 35 | 36 | return servers.length !== nextServers.length; 37 | } 38 | 39 | function registerListServerCommand(cmd: Cliffy.Command) { 40 | cmd.command( 41 | "list", 42 | new Cliffy.Command().description( 43 | "List known replica servers.", 44 | ) 45 | .action( 46 | () => { 47 | const servers = getServers(); 48 | 49 | new Cliffy.Table().body(servers.map((server) => [server])).border( 50 | true, 51 | ).render(); 52 | 53 | Deno.exit(0); 54 | }, 55 | ), 56 | ); 57 | } 58 | 59 | function registerAddServerCommand(cmd: Cliffy.Command) { 60 | cmd.command( 61 | "add", 62 | new Cliffy.Command() 63 | .arguments("") 64 | .description( 65 | "Add a URL to the list of known replica servers.", 66 | ) 67 | .action( 68 | (_flags, url) => { 69 | try { 70 | addServer(url); 71 | logSuccess(`Added ${url} to known replica servers.`); 72 | Deno.exit(0); 73 | } catch (err) { 74 | console.log(err.message); 75 | logWarning(`Couldn't add ${url}`); 76 | Deno.exit(1); 77 | } 78 | }, 79 | ), 80 | ); 81 | } 82 | 83 | function registerRemoveServerCommand(cmd: Cliffy.Command) { 84 | cmd.command( 85 | "remove", 86 | new Cliffy.Command().description( 87 | "Remove a known replica server.", 88 | ).option("--server ", "Replica server URL", { 89 | required: false, 90 | }) 91 | .action( 92 | async ({ server }) => { 93 | const servers = getServers(); 94 | 95 | const serverToRemove = server || await Cliffy.Select.prompt({ 96 | message: "Choose a server to remove", 97 | options: servers, 98 | }); 99 | 100 | const removed = removeServer(serverToRemove); 101 | 102 | if (removed) { 103 | logSuccess(`Removed ${serverToRemove} from known replica servers.`); 104 | } else { 105 | logWarning( 106 | `Nothing was removed. Didn't know about ${serverToRemove} to begin with.`, 107 | ); 108 | } 109 | 110 | Deno.exit(0); 111 | }, 112 | ), 113 | ); 114 | } 115 | 116 | export function registerServerCommands(cmd: Cliffy.Command) { 117 | const serverCommand = new Cliffy.Command().description( 118 | "Manage known replica servers.", 119 | ).action(() => { 120 | serverCommand.showHelp(); 121 | }); 122 | 123 | registerListServerCommand(serverCommand); 124 | registerAddServerCommand(serverCommand); 125 | registerRemoveServerCommand(serverCommand); 126 | 127 | cmd.command( 128 | "servers", 129 | serverCommand, 130 | ); 131 | } 132 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Earthstar CLI 2 | 3 | > ### **🚨🚨🚨 The Earthstar CLI is not under active development**! Please check out [user-scripts](https://github.com/earthstar-project/user_scripts) instead, which offers pretty much all of the same functionality as the CLI, but with the benefit that you can extend functionality with your own scripts, and tweak existing ones. 4 | 5 | --- 6 | 7 | A complete command-line suite for everything Earthstar. Manage identities, back 8 | up shares on your computer, and sync with replica servers over the internet. 9 | 10 | - `earthstar identities` - Generate and manage Earthstar identities. 11 | - `earthstar shares` - Create, sync, and interact with shares. 12 | - `earthstar servers` - Add and remove replica servers you want to sync with. 13 | - `earthstar upgrade` - Upgrade the CLI to the latest version. 14 | 15 | This tool also provides a special filesystem synchronisation feature, allowing 16 | you to use your filesystem as a way to view and modify share data. More on that 17 | below! 18 | 19 | ## Installation 20 | 21 | In time we will have pre-compiled binaries of this tool. Until then, you'll need 22 | to have Deno installed 23 | ([instructions here](https://deno.land/manual/getting_started/installation)). 24 | 25 | > If you had the previous Node version of the CLI installed, make sure to 26 | > uninstall it using `npm uninstall -g earthstar-cli`. 27 | 28 | Once Deno is installed, run the following command in your terminal: 29 | 30 | `deno install --allow-read --allow-write --allow-net --allow-run --allow-env --no-check --unstable -f --location https://earthstar-project.org -n earthstar https://deno.land/x/earthstar_cli/src/main.ts` 31 | 32 | There are a few permission flags there. Here is what they are for: 33 | 34 | - `--allow-read` - Reading Earthstar databases on the filesystem, filesystem 35 | sync. 36 | - `--allow-write` - Writing Earthstar databases to the filesystem, filesystem 37 | sync. 38 | - `--allow-net` - Synchronising with remote servers, checking for latest CLI 39 | version. 40 | - `--allow-run` - Running the upgrade script. 41 | - `--allow-env` - Gets your HOME path when suggesting where to store your 42 | shares. 43 | 44 | You will see a message once installation is complete. 45 | 46 | > If you ever want to uninstall, run `deno uninstall earthstar`. 47 | 48 | ## `earthstar identities` 49 | 50 | Create new Earthstar identities or save existing ones, as well as set a current 51 | identity which is used by default for commands which write data to shares. 52 | 53 | - `list` - List all saved identities. 54 | - `switch` - Switch the identity used by default for setting data. 55 | - `generate ` - Generate a new identity with a shortname. 56 | - `add
` - Manually add an existing identity with a address 57 | and secret. 58 | - `remove` - Forget an identity. 59 | - `info` - Display an identity's public address and/or secret. 60 | 61 | Extra flags can be found for each of these commands by using the `--help` flag. 62 | 63 | ## `earthstar shares` 64 | 65 | Manage, create, modify, and sync your Earthstar shares. Take it one step 66 | further, and view and modify their contents through your filesystem! 67 | 68 | Your shares are saved locally as Sqlite databases in a directory of your choice, 69 | making them fully functional even when you're offline. 70 | 71 | - `generate ` - Generate a new share address using a shortname you 72 | provide. 73 | - `add ` - Add an existing share using its public address. 74 | - `list` - List all known shares. 75 | - `remove` - Forget a known share. 76 | - `set` - Write data to a path on a share. 77 | - `paths` - List all document paths on a share. 78 | - `latest` - Display the latest document at a given path. 79 | - `contents` - Get the latest content at a given path. 80 | - `sync` - Sync your shares with known replica servers OR a local share 81 | database. 82 | - `sync-files` - Bidirectionally synchronise a share's documents with a 83 | directory on your filesystem. 84 | - `set-share-dir` - Set the filesystem directory where your share data is 85 | stored. 86 | 87 | Extra flags can be found for each of these commands by using the `--help` flag. 88 | 89 | ## `earthstar servers` 90 | 91 | Manage a list of replica servers you know and trust, and which will be synced 92 | with when you run `earthstar shares sync`. 93 | 94 | Even if you have many shares, replica servers will only have knowledge of those 95 | they knew of beforehand. Your shares will never be leaked to replica servers 96 | that don't know about them already. 97 | 98 | - `list` - List known replica servers 99 | - `add ` - Add a replica server by its URL. 100 | - `remove` - Forget a replica server. 101 | 102 | Extra flags can be found for each of these commands by using the `--help` flag. 103 | 104 | ## Filesystem synchronisation 105 | 106 | `earthstar shares sync-files` synchronises a share with a directory, 107 | representing a share's documents as files on your computer. If you modify those 108 | files, those modifications can be synchronised _back_ to the share, and synced 109 | with other peers! 110 | 111 | This makes it possible for you to interact with share documents with the tools 112 | you already know and use. 113 | 114 | - Synchronise a knowledgebase of markdown files across different machines and 115 | users (e.g. Obsidian) 116 | - Create websites with your friends (and serve it from one of your replica 117 | servers!) 118 | - Start a sneakernet of funny images you pass by USB key, synced from one 119 | computer to the next. 120 | 121 | There are some caveats: 122 | 123 | - **Earthstar's current maximum size for documents is 4 megabytes**. If you try 124 | to sync a document larger than this, sync will throw a warning. This limit 125 | will be addressed in the near future. 126 | - Binary files will be encoded to base64, increasing their size by ~30%. This 127 | will also be addressed in the near future. 128 | - Writing to certain 'owned' paths may not be permitted, throwing an error when 129 | you try to sync. If you don't care about losing the local data, you can use 130 | the `--overwriteFilesAtOwnedPaths` flag. 131 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright © 2007 Free Software Foundation, Inc. 5 | 6 | Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 7 | 8 | This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 9 | 10 | 0. Additional Definitions. 11 | As used herein, “this License” refers to version 3 of the GNU Lesser General Public License, and the “GNU GPL” refers to version 3 of the GNU General Public License. 12 | 13 | “The Library” refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. 14 | 15 | An “Application” is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. 16 | 17 | A “Combined Work” is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the “Linked Version”. 18 | 19 | The “Minimal Corresponding Source” for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. 20 | 21 | The “Corresponding Application Code” for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 22 | 23 | 1. Exception to Section 3 of the GNU GPL. 24 | You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 25 | 26 | 2. Conveying Modified Versions. 27 | If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: 28 | 29 | a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or 30 | b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 31 | 3. Object Code Incorporating Material from Library Header Files. 32 | The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: 33 | 34 | a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. 35 | b) Accompany the object code with a copy of the GNU GPL and this license document. 36 | 4. Combined Works. 37 | You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: 38 | 39 | a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. 40 | b) Accompany the Combined Work with a copy of the GNU GPL and this license document. 41 | c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. 42 | d) Do one of the following: 43 | 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 44 | 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. 45 | e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 46 | 5. Combined Libraries. 47 | You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: 48 | 49 | a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. 50 | b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 51 | 6. Revised Versions of the GNU Lesser General Public License. 52 | The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 53 | 54 | Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. 55 | 56 | If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. 57 | 58 | -------------------------------------------------------------------------------- /src/identity.ts: -------------------------------------------------------------------------------- 1 | import { Cliffy, Earthstar } from "../deps.ts"; 2 | import { logSuccess, logWarning } from "./util.ts"; 3 | 4 | const LS_IDENTITIES_KEY = "identities"; 5 | const LS_CURRENT_IDENTITY_KEY = "current_identity"; 6 | 7 | export function getIdentities(): Record { 8 | const result = localStorage.getItem(LS_IDENTITIES_KEY); 9 | return result ? JSON.parse(result) : {}; 10 | } 11 | 12 | function setIdentities(identities: Record): void { 13 | localStorage.setItem(LS_IDENTITIES_KEY, JSON.stringify(identities)); 14 | } 15 | 16 | function addIdentity(identity: Earthstar.AuthorKeypair) { 17 | const identities = getIdentities(); 18 | const next = { ...identities, [identity.address]: identity.secret }; 19 | setIdentities(next); 20 | } 21 | 22 | function removeIdentity(address: string): boolean { 23 | const identities = getIdentities(); 24 | 25 | if (identities[address]) { 26 | delete identities[address]; 27 | setIdentities(identities); 28 | 29 | return true; 30 | } 31 | 32 | return false; 33 | } 34 | 35 | export function getCurrentIdentity(): string | null { 36 | return localStorage.getItem(LS_CURRENT_IDENTITY_KEY); 37 | } 38 | 39 | function setCurrentIdentity(address: string): boolean { 40 | const identities = getIdentities(); 41 | 42 | if (identities[address]) { 43 | localStorage.setItem(LS_CURRENT_IDENTITY_KEY, address); 44 | 45 | return true; 46 | } 47 | 48 | return false; 49 | } 50 | 51 | function clearCurrentIdentity() { 52 | localStorage.removeItem(LS_CURRENT_IDENTITY_KEY); 53 | 54 | return true; 55 | } 56 | 57 | function registerListIdentityCommand(cmd: Cliffy.Command) { 58 | cmd.command( 59 | "list", 60 | new Cliffy.Command() 61 | .description("List all saved identities") 62 | .action(() => { 63 | const addresses = Object.keys(getIdentities()); 64 | 65 | if (addresses.length === 0) { 66 | console.log("No identities have been saved."); 67 | Deno.exit(); 68 | } 69 | 70 | const currentIdentity = getCurrentIdentity(); 71 | 72 | const rows = addresses.map((address) => { 73 | return [address, address === currentIdentity ? "Yes" : ""]; 74 | }); 75 | 76 | new Cliffy.Table().header(["Address", "Selected"]).border(true) 77 | .body( 78 | rows, 79 | ).render(); 80 | 81 | Deno.exit(0); 82 | }), 83 | ); 84 | } 85 | 86 | function registerGenerateIdentityCommand(cmd: Cliffy.Command) { 87 | cmd.command( 88 | "generate", 89 | new Cliffy.Command() 90 | .arguments("") 91 | .description("Generate a new identity") 92 | .option("-a, --add [type:boolean]", "Add to saved identities", { 93 | default: true, 94 | }) 95 | .option("-c, --current [type:boolean]", "Set as current identity", { 96 | depends: ["add"], 97 | default: false, 98 | }) 99 | .action( 100 | async ( 101 | { add, current }, 102 | name, 103 | ) => { 104 | const result = await Earthstar.Crypto.generateAuthorKeypair(name); 105 | 106 | if (Earthstar.isErr(result)) { 107 | console.log(`${result}`); 108 | Deno.exit(1); 109 | } 110 | 111 | if (add) { 112 | addIdentity(result); 113 | } 114 | 115 | if (current) { 116 | setCurrentIdentity(result.address); 117 | } 118 | 119 | if (!add) { 120 | const encoded = new TextEncoder().encode( 121 | (result as Earthstar.AuthorKeypair).address + "\n" + 122 | (result as Earthstar.AuthorKeypair).secret + "\n", 123 | ); 124 | 125 | await Deno.stdout.write(encoded); 126 | Deno.stdout.close(); 127 | } else { 128 | const { name } = Earthstar.parseAuthorAddress(result.address); 129 | 130 | logSuccess(`Added @${name} to stored identities.`); 131 | 132 | Deno.exit(0); 133 | } 134 | }, 135 | ), 136 | ); 137 | } 138 | 139 | function registerSwitchIdentityCommand(cmd: Cliffy.Command) { 140 | cmd.command( 141 | "switch", 142 | new Cliffy.Command() 143 | .description("Set the current identity") 144 | .action(async () => { 145 | const identities = Object.keys(getIdentities()); 146 | 147 | const address: string = await Cliffy.Select.prompt({ 148 | message: "Select which identity to use to sign documents", 149 | options: [...identities, "None"], 150 | }); 151 | 152 | if (address !== "None") { 153 | setCurrentIdentity(address); 154 | } else { 155 | clearCurrentIdentity(); 156 | } 157 | 158 | Deno.exit(0); 159 | }), 160 | ); 161 | } 162 | 163 | function registerAddIdentityCommand(cmd: Cliffy.Command) { 164 | cmd.command( 165 | "add", 166 | new Cliffy.Command() 167 | .arguments("
") 168 | .description("Add an existing identity") 169 | .option("-c, --current [type:boolean]", "Set as current identity", { 170 | default: false, 171 | }) 172 | .action( 173 | async ({ current }: { current: boolean }, address, secret) => { 174 | const keypair: Earthstar.AuthorKeypair = { address, secret }; 175 | 176 | const result = await Earthstar.Crypto.checkAuthorKeypairIsValid( 177 | keypair, 178 | ); 179 | 180 | if (Earthstar.isErr(result)) { 181 | logWarning("Could not add identity."); 182 | console.log(`${result.message}`); 183 | Deno.exit(1); 184 | } 185 | 186 | addIdentity(keypair); 187 | 188 | if (current) { 189 | setCurrentIdentity(address); 190 | } 191 | 192 | logSuccess(`Added ${address}`); 193 | 194 | Deno.exit(0); 195 | }, 196 | ), 197 | ); 198 | } 199 | 200 | function registerRemoveIdentityCommand(cmd: Cliffy.Command) { 201 | cmd.command( 202 | "remove", 203 | new Cliffy.Command() 204 | .description("Remove a known identity") 205 | .option("--idAddress ", "The address to remove", { 206 | required: false, 207 | }) 208 | .action(async ({ idAddress }) => { 209 | const identities = getIdentities(); 210 | 211 | const address = idAddress || await Cliffy.Select.prompt({ 212 | message: "Choose which identity to remove", 213 | options: Object.keys(identities), 214 | }); 215 | 216 | const currentIdentity = getCurrentIdentity(); 217 | 218 | if (!identities[address]) { 219 | console.log(`No known identity with the address ${address}`); 220 | return Deno.exit(0); 221 | } 222 | 223 | const isSure = await Cliffy.Confirm.prompt( 224 | "This identity and its secret will be forgotten. Are you sure you want to do this?", 225 | ); 226 | 227 | if (!isSure) { 228 | return Deno.exit(0); 229 | } 230 | removeIdentity(address); 231 | 232 | if (address === currentIdentity) { 233 | clearCurrentIdentity(); 234 | } 235 | 236 | logSuccess(`Removed ${address}`); 237 | 238 | Deno.exit(0); 239 | }), 240 | ); 241 | } 242 | 243 | function registerInfoIdentityCommand(cmd: Cliffy.Command) { 244 | cmd.command( 245 | "info", 246 | new Cliffy.Command().description( 247 | "Show a stored identity's full address and secret", 248 | ).option( 249 | "--idAddress ", 250 | "The address to show info for.", 251 | { 252 | required: false, 253 | }, 254 | ) 255 | .option( 256 | "--current [current:boolean]", 257 | "Use the currently selected identity", 258 | { 259 | required: false, 260 | conflicts: ["idAddress"], 261 | }, 262 | ) 263 | .option( 264 | "--onlyAddress [onlyAddress:boolean]", 265 | "Only output the identity's address.", 266 | { 267 | required: false, 268 | conflicts: ["onlySecret"], 269 | }, 270 | ).option( 271 | "--onlySecret [onlySecret:boolean]", 272 | "Only output the identity's secret.", 273 | { 274 | required: false, 275 | conflicts: ["onlyAddress"], 276 | }, 277 | ).action(async ({ current, idAddress, onlyAddress, onlySecret }) => { 278 | const identities = getIdentities(); 279 | 280 | if (Object.keys(identities).length === 0) { 281 | console.log("No identities have been stored."); 282 | Deno.exit(0); 283 | } 284 | 285 | const address = (current && 286 | getCurrentIdentity()) || 287 | idAddress || await Cliffy.Select.prompt({ 288 | message: "Choose which identity to show info for", 289 | options: Object.keys(identities), 290 | }); 291 | 292 | if (!identities[address]) { 293 | console.log(`No known identity with the address ${address}`); 294 | return Deno.exit(0); 295 | } 296 | 297 | const secret = identities[address]; 298 | 299 | if (onlyAddress) { 300 | console.log(address); 301 | } else if (onlySecret) { 302 | console.log(secret); 303 | } else { 304 | new Cliffy.Table().body([["Address", address], [ 305 | "Secret", 306 | secret, 307 | ]]) 308 | .border(true).render(); 309 | } 310 | 311 | Deno.exit(0); 312 | }), 313 | ); 314 | } 315 | 316 | export function registerIdentityCommand(cmd: Cliffy.Command) { 317 | const identityCommand = new Cliffy.Command().description( 318 | "Manage identities used to sign documents.", 319 | ).action(() => { 320 | identityCommand.showHelp(); 321 | }); 322 | 323 | registerGenerateIdentityCommand(identityCommand); 324 | registerAddIdentityCommand(identityCommand); 325 | registerRemoveIdentityCommand(identityCommand); 326 | registerListIdentityCommand(identityCommand); 327 | registerSwitchIdentityCommand(identityCommand); 328 | registerInfoIdentityCommand(identityCommand); 329 | 330 | cmd.command( 331 | "identities", 332 | identityCommand, 333 | ); 334 | } 335 | -------------------------------------------------------------------------------- /src/share.ts: -------------------------------------------------------------------------------- 1 | import { Cliffy, distanceToNow, Earthstar } from "../deps.ts"; 2 | import { getCurrentIdentity, getIdentities } from "./identity.ts"; 3 | import * as path from "https://deno.land/std@0.131.0/path/mod.ts"; 4 | import home_dir from "https://deno.land/x/dir@v1.2.0/home_dir/mod.ts"; 5 | import { logEmphasis, logSuccess, logWarning } from "./util.ts"; 6 | import { getDirAssociatedShare } from "https://deno.land/x/earthstar@v9.3.3/src/sync-fs/util.ts"; 7 | import { getServers } from "./servers.ts"; 8 | import { ensureDir } from "https://deno.land/std@0.132.0/fs/mod.ts"; 9 | 10 | const LS_SHARE_DIR_KEY = "shares_dir"; 11 | 12 | function openReplica(path: string) { 13 | const driver = new Earthstar.ReplicaDriverSqlite({ 14 | filename: path, 15 | mode: "open", 16 | share: null, 17 | }); 18 | 19 | return new Earthstar.Replica( 20 | driver.share, 21 | Earthstar.FormatValidatorEs4, 22 | driver, 23 | ); 24 | } 25 | 26 | async function openShare(address: string) { 27 | const sharesDir = await getSharesDir(); 28 | 29 | const sharePath = path.join(sharesDir, `${address}.sqlite`); 30 | 31 | return openReplica(sharePath); 32 | } 33 | 34 | async function setShareDir(message: string) { 35 | const newSharesDir = await Cliffy.Input.prompt({ 36 | message, 37 | default: path.join(home_dir() || "", "Shares"), 38 | validate: async (input) => { 39 | try { 40 | const dirStat = await Deno.stat(input); 41 | 42 | return dirStat.isDirectory; 43 | } catch (err) { 44 | return err.message; 45 | } 46 | }, 47 | }); 48 | 49 | localStorage.setItem(LS_SHARE_DIR_KEY, newSharesDir); 50 | 51 | await ensureDir(newSharesDir); 52 | 53 | return newSharesDir; 54 | } 55 | 56 | async function getSharesDir(): Promise { 57 | const sharesDir = localStorage.getItem(LS_SHARE_DIR_KEY); 58 | 59 | if (sharesDir) { 60 | try { 61 | await Deno.stat(sharesDir); 62 | 63 | return sharesDir; 64 | } catch { 65 | const newSharesDir = await setShareDir( 66 | "No directory for storing shares wasn't where it was expected to be. Where should it be?", 67 | ); 68 | 69 | return newSharesDir; 70 | } 71 | } 72 | 73 | const newSharesDir = await setShareDir( 74 | "No directory for storing shares has been set yet. Where you would you like it?", 75 | ); 76 | 77 | return newSharesDir; 78 | } 79 | 80 | async function findRootManifestDirUpwards(dir: string): Promise { 81 | try { 82 | await Deno.stat(path.join(dir, ".es-fs-manifest")); 83 | 84 | return dir; 85 | } catch { 86 | const parentDir = path.resolve(dir, ".."); 87 | 88 | if (parentDir === dir) { 89 | // We've reached the top, with nowhere to go. 90 | return null; 91 | } 92 | 93 | return findRootManifestDirUpwards(parentDir); 94 | } 95 | } 96 | 97 | async function getPeer() { 98 | const sharesDir = await getSharesDir(); 99 | 100 | const peer = new Earthstar.Peer(); 101 | 102 | for await (const dirEntry of Deno.readDir(sharesDir)) { 103 | if (dirEntry.isFile && dirEntry.name.endsWith(".sqlite")) { 104 | try { 105 | const replica = openReplica(path.join(sharesDir, dirEntry.name)); 106 | 107 | peer.addReplica(replica); 108 | } catch (err) { 109 | logWarning(`Couldn't read ${dirEntry.name}:`); 110 | console.error(err); 111 | } 112 | } 113 | } 114 | 115 | return peer; 116 | } 117 | 118 | async function promptShare() { 119 | const peer = await getPeer(); 120 | const shares = peer.shares(); 121 | 122 | for (const replica of peer.replicas()) { 123 | await replica.close(false); 124 | } 125 | 126 | return Cliffy.Input.prompt({ 127 | message: "Choose a share", 128 | suggestions: shares, 129 | validate: (input) => { 130 | return shares.includes(input); 131 | }, 132 | }); 133 | } 134 | 135 | async function promptPath(replica: Earthstar.Replica, allowNew?: boolean) { 136 | const docs = await replica.getLatestDocs(); 137 | const paths = docs.map((doc) => doc.path); 138 | 139 | return Cliffy.Input.prompt({ 140 | message: "Choose a path", 141 | list: true, 142 | suggestions: paths, 143 | validate: async (input) => { 144 | if (allowNew) { 145 | return true; 146 | } 147 | 148 | const res = await replica.getLatestDocAtPath(input); 149 | 150 | if (!res) { 151 | return "No such path exists."; 152 | } 153 | 154 | return true; 155 | }, 156 | }); 157 | } 158 | 159 | function logDoc(doc: Earthstar.Doc) { 160 | const docDate = new Date(doc.timestamp / 1000); 161 | 162 | const table = new Cliffy.Table(); 163 | 164 | table.body( 165 | [ 166 | ["Path", doc.path], 167 | ["Content", doc.content], 168 | ["Author", doc.author], 169 | [ 170 | "Timestamp", 171 | `${doc.timestamp} (${distanceToNow(docDate, { addSuffix: true })})`, 172 | ], 173 | ["Signature", doc.signature], 174 | ["Content hash", doc.contentHash], 175 | ["Format", doc.format], 176 | ], 177 | ).border(true).maxColWidth(50) 178 | .render(); 179 | } 180 | 181 | function registerGenerateShareCommand(cmd: Cliffy.Command) { 182 | cmd.command( 183 | "generate", 184 | new Cliffy.Command() 185 | .arguments("") 186 | .description( 187 | "Generate a new share address using a human readable name.", 188 | ).option( 189 | "-a, --add [type:boolean]", 190 | "Add to saved shares", 191 | { 192 | default: true, 193 | }, 194 | ).action( 195 | async ( 196 | { add }, 197 | name: string, 198 | ) => { 199 | const result = Earthstar.generateShareAddress(name); 200 | 201 | if (Earthstar.isErr(result)) { 202 | logWarning("Could not generate share address."); 203 | console.error(result); 204 | Deno.exit(1); 205 | } 206 | 207 | logSuccess("Generated share address."); 208 | 209 | if (!add) { 210 | console.log(result); 211 | Deno.exit(0); 212 | } 213 | 214 | const dirPath = await getSharesDir(); 215 | const dbPath = path.join(dirPath, `${result}.sqlite`); 216 | 217 | try { 218 | const driver = new Earthstar.ReplicaDriverSqlite({ 219 | filename: dbPath, 220 | mode: "create", 221 | share: result, 222 | }); 223 | 224 | logSuccess(`Added ${driver.share}`); 225 | 226 | await driver.close(false); 227 | Deno.exit(0); 228 | } catch (err) { 229 | logWarning("Failed to persist share."); 230 | console.error(err); 231 | Deno.exit(1); 232 | } 233 | }, 234 | ), 235 | ); 236 | } 237 | 238 | function registerAddShareCommand(cmd: Cliffy.Command) { 239 | cmd.command( 240 | "add", 241 | new Cliffy.Command() 242 | .arguments("") 243 | .description("Add a share by address.").action( 244 | async ( 245 | _flags, 246 | shareAddress: string, 247 | ) => { 248 | const addressIsValidResult = Earthstar.checkShareIsValid( 249 | shareAddress, 250 | ); 251 | 252 | if (Earthstar.isErr(addressIsValidResult)) { 253 | logWarning(`Could not add ${shareAddress}`); 254 | console.error(`${addressIsValidResult}`); 255 | Deno.exit(1); 256 | } 257 | 258 | const dirPath = await getSharesDir(); 259 | const dbPath = path.join(dirPath, `${shareAddress}.sqlite`); 260 | 261 | try { 262 | const driver = new Earthstar.ReplicaDriverSqlite({ 263 | filename: dbPath, 264 | mode: "create", 265 | share: shareAddress, 266 | }); 267 | 268 | logSuccess(`Added ${driver.share}`); 269 | 270 | await driver.close(false); 271 | Deno.exit(0); 272 | } catch (err) { 273 | logWarning("Failed to persist share."); 274 | console.error(err); 275 | Deno.exit(1); 276 | } 277 | }, 278 | ), 279 | ); 280 | } 281 | 282 | function registerChangeDirShareCommand(cmd: Cliffy.Command) { 283 | cmd.command( 284 | "set-share-dir", 285 | new Cliffy.Command().description( 286 | "Change where earthstar-cli persists and looks for shares", 287 | ).action( 288 | async (_flags) => { 289 | const res = await setShareDir( 290 | "Where should earthstar persist and look for shares from now on?", 291 | ); 292 | 293 | logSuccess(`Set share directory to ${res}`); 294 | }, 295 | ), 296 | ); 297 | } 298 | 299 | function registerLsShareCommand(cmd: Cliffy.Command) { 300 | cmd.command( 301 | "list", 302 | new Cliffy.Command().description("List all stored shares.") 303 | .option("-s, --suffix [type:boolean]", "Show address suffixes", { 304 | default: false, 305 | }) 306 | .action( 307 | async ({ suffix }) => { 308 | const peer = await getPeer(); 309 | const shareDir = await getSharesDir(); 310 | 311 | if (peer.replicas().length === 0) { 312 | console.log("No known shares. Add some with earthstar shares add"); 313 | } 314 | 315 | const rows: string[][] = []; 316 | 317 | for await (const replica of peer.replicas()) { 318 | const address = replica.share; 319 | 320 | const parsed = Earthstar.parseShareAddress( 321 | address, 322 | ) as Earthstar.ParsedAddress; 323 | 324 | const docCount = await replica.getLatestDocs(); 325 | 326 | if (suffix) { 327 | rows.push([ 328 | address, 329 | `${docCount.length}`, 330 | path.join( 331 | shareDir, 332 | `${parsed.address}.sqlite`, 333 | ), 334 | ]); 335 | } else { 336 | rows.push([ 337 | `+${parsed.name}`, 338 | `${docCount.length}`, 339 | path.join( 340 | shareDir, 341 | `${parsed.name}.***.sqlite`, 342 | ), 343 | ]); 344 | } 345 | } 346 | 347 | console.log("All shares stored at:", shareDir); 348 | 349 | new Cliffy.Table().header([ 350 | "Address", 351 | "Docs", 352 | "Filepath", 353 | ]).body(rows).border(true).render(); 354 | 355 | Deno.exit(0); 356 | }, 357 | ), 358 | ); 359 | } 360 | 361 | function registerSetShareCommand(cmd: Cliffy.Command) { 362 | cmd.command( 363 | "set", 364 | new Cliffy.Command().description("Set a document's contents.") 365 | .option("--idAddress ", "Identity address to use", { 366 | depends: ["idSecret"], 367 | required: false, 368 | }) 369 | .option("--idSecret ", "Identity secret to use", { 370 | depends: ["idAddress"], 371 | required: false, 372 | }) 373 | .option("--share ", "Share address", { 374 | required: false, 375 | }) 376 | .option("--path ", "Document path", { 377 | required: false, 378 | }) 379 | .option("--content ", "Document content", { 380 | required: false, 381 | }) 382 | .action( 383 | async ( 384 | { idAddress, idSecret, share, path, content }, 385 | ) => { 386 | let keypair: Earthstar.AuthorKeypair | null = null; 387 | 388 | if (idAddress && idSecret) { 389 | const keypair = { 390 | address: idAddress, 391 | secret: idSecret, 392 | }; 393 | 394 | const isValidRes = await Earthstar.Crypto.checkAuthorKeypairIsValid( 395 | keypair, 396 | ); 397 | 398 | if (Earthstar.isErr(isValidRes)) { 399 | logWarning("A valid keypair was not provided."); 400 | console.error(isValidRes); 401 | Deno.exit(1); 402 | } 403 | } else { 404 | const currentIdentity = getCurrentIdentity(); 405 | 406 | if (currentIdentity) { 407 | const secret = getIdentities()[currentIdentity]; 408 | 409 | keypair = { 410 | address: currentIdentity, 411 | secret, 412 | }; 413 | } 414 | } 415 | 416 | if (keypair === null) { 417 | logWarning( 418 | "Could not get the identity to set the document with", 419 | ); 420 | Deno.exit(1); 421 | } 422 | 423 | const address = share || await promptShare(); 424 | const replica = await openShare(address); 425 | const pathToUse = path || await promptPath(replica, true); 426 | const contentToUse = content || await Cliffy.Input.prompt({ 427 | message: "Enter document content", 428 | }); 429 | 430 | const res = await replica.set(keypair, { 431 | content: contentToUse, 432 | path: pathToUse, 433 | format: "es.4", 434 | }); 435 | 436 | if (res.kind === "failure") { 437 | logWarning("Could not set the document."); 438 | console.error(res.reason); 439 | await replica.close(false); 440 | Deno.exit(1); 441 | } 442 | 443 | if (res.kind === "success") { 444 | logSuccess("Successfully wrote document."); 445 | logDoc(res.doc); 446 | } 447 | 448 | await replica.close(false); 449 | Deno.exit(0); 450 | }, 451 | ), 452 | ); 453 | } 454 | 455 | function registerPathsShareCommand(cmd: Cliffy.Command) { 456 | cmd.command( 457 | "paths", 458 | new Cliffy.Command().description("Get the paths of this share's documents.") 459 | .option("--share ", "Share address", { 460 | required: false, 461 | }) 462 | .action( 463 | async ({ share }) => { 464 | const address = share || await promptShare(); 465 | 466 | const replica = await openShare(address); 467 | 468 | const latestDocs = await replica.getLatestDocs(); 469 | 470 | const paths = latestDocs.map((doc) => doc.path); 471 | 472 | for (const path of paths) { 473 | console.log(path); 474 | } 475 | 476 | await replica.close(false); 477 | Deno.exit(0); 478 | }, 479 | ), 480 | ); 481 | } 482 | 483 | function registerGetLatestShareCommand(cmd: Cliffy.Command) { 484 | cmd.command( 485 | "latest", 486 | new Cliffy.Command().description( 487 | "Get the latest document at a share's path.", 488 | ).option("--share ", "Share address", { 489 | required: false, 490 | }) 491 | .option("--path ", "Document path", { 492 | required: false, 493 | }) 494 | .action( 495 | async ({ share, path }) => { 496 | const address = share || await promptShare(); 497 | const replica = await openShare(address); 498 | const pathToUse = path || await promptPath(replica); 499 | const latestDoc = await replica.getLatestDocAtPath(pathToUse); 500 | 501 | if (!latestDoc) { 502 | console.log(`No document exists at ${pathToUse}`); 503 | await replica.close(false); 504 | Deno.exit(1); 505 | } 506 | 507 | logDoc(latestDoc); 508 | await replica.close(false); 509 | Deno.exit(0); 510 | }, 511 | ), 512 | ); 513 | } 514 | 515 | function registerContentShareCommand(cmd: Cliffy.Command) { 516 | cmd.command( 517 | "contents", 518 | new Cliffy.Command().description( 519 | "Get the contents of the latest document at this share's path", 520 | ) 521 | .option("--share ", "Share address", { 522 | required: false, 523 | }) 524 | .option("--path ", "Document path", { 525 | required: false, 526 | }) 527 | .action( 528 | async ({ share, path }) => { 529 | const address = share || await promptShare(); 530 | const replica = await openShare(address); 531 | const pathToUse = path || await promptPath(replica); 532 | const latestDoc = await replica.getLatestDocAtPath(pathToUse); 533 | 534 | if (!latestDoc) { 535 | console.log(`No document exists at ${pathToUse}`); 536 | await replica.close(false); 537 | Deno.exit(1); 538 | } 539 | 540 | console.log(latestDoc.content); 541 | await replica.close(false); 542 | Deno.exit(0); 543 | }, 544 | ), 545 | ); 546 | } 547 | 548 | function registerSyncShareCommand(cmd: Cliffy.Command) { 549 | cmd.command( 550 | "sync", 551 | new Cliffy.Command().description( 552 | "Sync this document with a known replica servers or a local Earthstar database..", 553 | ).option( 554 | "--dbPath ", 555 | "The path of a Sqlite Earthstar database to sync", 556 | { 557 | conflicts: ["serverUrl"], 558 | }, 559 | ).option( 560 | "--serverUrl ", 561 | "The path of a Sqlite Earthstar database to sync", 562 | { 563 | conflicts: ["dbPath"], 564 | }, 565 | ) 566 | .action( 567 | async ( 568 | { dbPath, serverUrl }, 569 | ) => { 570 | const peer = await getPeer(); 571 | 572 | const servers = getServers(); 573 | 574 | if (!dbPath && !serverUrl && servers.length === 0) { 575 | console.log("No known replica servers to sync with."); 576 | Deno.exit(0); 577 | } 578 | 579 | const thingsToSyncWith: (string | Earthstar.Peer)[] = []; 580 | 581 | if (dbPath) { 582 | const otherReplica = openReplica(dbPath); 583 | const otherPeer = new Earthstar.Peer(); 584 | otherPeer.addReplica(otherReplica); 585 | thingsToSyncWith.push(otherPeer); 586 | } else if (serverUrl) { 587 | thingsToSyncWith.push(serverUrl); 588 | } else { 589 | thingsToSyncWith.push(...servers); 590 | } 591 | 592 | peer.syncerStatuses.bus.on("changed", (_key) => { 593 | const rows = []; 594 | 595 | for ( 596 | const [connection, statuses] of peer.syncerStatuses.entries() 597 | ) { 598 | rows.push([new Cliffy.Cell(connection).colSpan(3)]); 599 | rows.push(["Share", "Pulled", "New"]); 600 | 601 | Object.keys(statuses).forEach((shareAddress) => { 602 | const { ingestedCount, pulledCount } = (statuses)[shareAddress]; 603 | 604 | const { name } = Earthstar.parseShareAddress(shareAddress); 605 | 606 | rows.push([ 607 | `+${name}`, 608 | `${pulledCount}`, 609 | `${ingestedCount}`, 610 | ]); 611 | }); 612 | } 613 | 614 | Cliffy.tty.clearTerminal(); 615 | 616 | if (dbPath) { 617 | console.log( 618 | `Syncing with ${dbPath}...`, 619 | ); 620 | } else if (serverUrl) { 621 | console.log( 622 | `Syncing with ${serverUrl}...`, 623 | ); 624 | } else { 625 | console.log( 626 | `Syncing with ${thingsToSyncWith.length} peer${ 627 | thingsToSyncWith.length > 1 ? "s" : "" 628 | }...`, 629 | ); 630 | } 631 | 632 | new Cliffy.Table().border(true).body(rows).render(); 633 | }); 634 | 635 | try { 636 | console.log("Syncing..."); 637 | 638 | await peer.syncUntilCaughtUp(thingsToSyncWith); 639 | 640 | logSuccess("Synced."); 641 | 642 | Deno.exit(0); 643 | } catch (err) { 644 | logWarning("Something went wrong when trying to sync!"); 645 | console.error(err); 646 | Deno.exit(1); 647 | } 648 | }, 649 | ), 650 | ); 651 | } 652 | 653 | function registerFsSyncShareCommand(cmd: Cliffy.Command) { 654 | cmd.command( 655 | "sync-files", 656 | new Cliffy.Command().description( 657 | "Sync a share's contents to the filesystem. This command will search for the closest directory which has been synced before and sync from there, working upwards the file directory tree. If no previously synced directory is found and the current working directory is empty, the current working directory will be synced.", 658 | ) 659 | .option("--share ", "Share address", { 660 | required: false, 661 | }) 662 | .option( 663 | "--dirPath ", 664 | "The path of the directory to sync with", 665 | { 666 | required: false, 667 | }, 668 | ).option("--idAddress ", "Identity address to use", { 669 | depends: ["idSecret"], 670 | required: false, 671 | }) 672 | .option("--idSecret ", "Identity secret to use", { 673 | depends: ["idAddress"], 674 | required: false, 675 | }) 676 | .option( 677 | "--allowUnsyncedDirWithFiles [type:boolean]", 678 | "Whether to allow syncing with a directory with existing files but which has never been synced with a share before.", 679 | { 680 | required: false, 681 | default: false, 682 | }, 683 | ) 684 | .option( 685 | "--overwriteFilesAtOwnedPaths [type:boolean]", 686 | "Whether to force overwrite files at paths the provided identity doesn't own.", 687 | { 688 | required: false, 689 | }, 690 | ) 691 | .action( 692 | async ( 693 | { 694 | idAddress, 695 | idSecret, 696 | allowUnsyncedDirWithFiles, 697 | share, 698 | dirPath, 699 | overwriteFilesAtOwnedPaths, 700 | }, 701 | ) => { 702 | let keypair: Earthstar.AuthorKeypair | null = null; 703 | 704 | if (idAddress && idSecret) { 705 | const keypair = { 706 | address: idAddress, 707 | secret: idSecret, 708 | }; 709 | 710 | const isValidRes = await Earthstar.Crypto.checkAuthorKeypairIsValid( 711 | keypair, 712 | ); 713 | 714 | if (Earthstar.isErr(isValidRes)) { 715 | logWarning("A valid keypair was not provided."); 716 | console.error(isValidRes.message); 717 | Deno.exit(1); 718 | } 719 | } else { 720 | const currentIdentity = getCurrentIdentity(); 721 | 722 | if (currentIdentity) { 723 | const secret = getIdentities()[currentIdentity]; 724 | 725 | keypair = { 726 | address: currentIdentity, 727 | secret, 728 | }; 729 | } 730 | } 731 | 732 | if (keypair === null) { 733 | logWarning( 734 | "Could not get the identity to set the document with", 735 | ); 736 | Deno.exit(1); 737 | } 738 | 739 | let dirToSyncWith = dirPath || Deno.cwd(); 740 | 741 | // Use dirPath flag if provided. 742 | 743 | // If not, then... 744 | // Check if the current directory has a manifest. 745 | // If it does, use this directory. 746 | // If it doesn't, traverse upwards until one is found. 747 | // If none is found, use this directory. 748 | 749 | if (!dirPath) { 750 | try { 751 | await Deno.stat(".es-fs-manifest"); 752 | } catch { 753 | const parentWithManifest = await findRootManifestDirUpwards( 754 | Deno.cwd(), 755 | ); 756 | 757 | if (parentWithManifest) { 758 | dirToSyncWith = parentWithManifest; 759 | } 760 | } 761 | } 762 | 763 | const associatedShare = await getDirAssociatedShare(dirToSyncWith); 764 | 765 | const address = associatedShare || share || await promptShare(); 766 | const replica = await openShare(address); 767 | 768 | const { name } = Earthstar.parseShareAddress(replica.share); 769 | 770 | try { 771 | await Earthstar.syncReplicaAndFsDir({ 772 | keypair, 773 | allowDirtyDirWithoutManifest: allowUnsyncedDirWithFiles, 774 | replica, 775 | dirPath: dirToSyncWith, 776 | overwriteFilesAtOwnedPaths: !!overwriteFilesAtOwnedPaths, 777 | }); 778 | 779 | logSuccess(`Synced +${name} with ${path.resolve(dirToSyncWith)}`); 780 | Deno.exit(0); 781 | } catch (err) { 782 | logWarning( 783 | `Could not sync +${name} with ${path.resolve(dirToSyncWith)}`, 784 | ); 785 | 786 | console.error(err.message); 787 | 788 | if (err.message.indexOf("can't write to path /") !== -1) { 789 | logEmphasis( 790 | "If you're fine with this file being overwritten by the one from the replica, you can resolve this problem with the --overwriteFilesAtOwnedPaths flag.", 791 | ); 792 | } 793 | 794 | Deno.exit(1); 795 | } 796 | }, 797 | ), 798 | ); 799 | } 800 | 801 | function registerRemoveShareCommand(cmd: Cliffy.Command) { 802 | cmd.command( 803 | "remove", 804 | new Cliffy.Command().description( 805 | "Remove a share from stored shares.", 806 | ).option("--share [type:string]", "Share address", { 807 | required: false, 808 | }) 809 | .action( 810 | async ({ share }) => { 811 | const address = share || await promptShare(); 812 | const sharesDir = await getSharesDir(); 813 | const sharePath = path.join(sharesDir, `${address}.sqlite`); 814 | 815 | const isSure = await Cliffy.Confirm.prompt( 816 | `The local replica of ${address} will be erased and forgotten. Are you sure you want to do this?`, 817 | ); 818 | 819 | if (!isSure) { 820 | Deno.exit(0); 821 | } 822 | 823 | try { 824 | await Deno.remove(sharePath); 825 | logSuccess(`Removed ${address}`); 826 | Deno.exit(0); 827 | } catch (err) { 828 | logWarning( 829 | `Something wefnt wrong when trying to remove ${address}`, 830 | ); 831 | console.error(err); 832 | Deno.exit(1); 833 | } 834 | }, 835 | ), 836 | ); 837 | } 838 | 839 | export function registerShareCommands(cmd: Cliffy.Command) { 840 | const shareCommand = new Cliffy.Command().description( 841 | "Manage Earthstar shares.", 842 | ).action(() => { 843 | shareCommand.showHelp(); 844 | }); 845 | 846 | registerGenerateShareCommand(shareCommand); 847 | registerAddShareCommand(shareCommand); 848 | registerLsShareCommand(shareCommand); 849 | registerRemoveShareCommand(shareCommand); 850 | registerSetShareCommand(shareCommand); 851 | registerPathsShareCommand(shareCommand); 852 | registerGetLatestShareCommand(shareCommand); 853 | registerContentShareCommand(shareCommand); 854 | registerSyncShareCommand(shareCommand); 855 | registerChangeDirShareCommand(shareCommand); 856 | registerFsSyncShareCommand(shareCommand); 857 | 858 | cmd.command( 859 | "shares", 860 | shareCommand, 861 | ); 862 | } 863 | --------------------------------------------------------------------------------