diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 8c14a19..997f669 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -1,37 +1,46 @@ # How to contribute We're happy you're considering contributing to the Write.as command-line client! It won't take long to get up to speed on this. Here are our development resources: * We do our project management in [Phabricator](https://phabricator.write.as/tag/write.as_cli/). * We accept and respond to bugs here on [GitHub](https://github.com/writeas/writeas-cli/issues). * We're usually in #writeas on freenode, but if not, find us on our [Slack channel](http://slack.write.as). ## Testing We try to write tests for all parts of the CLI, but aren't there yet. While not required, including tests with your new code will bring us closer to where we want to be and speed up our review. ## Submitting changes Please send a [pull request](https://github.com/writeas/writeas-cli/compare) with a clear list of what you've done. Please follow our coding conventions below and make sure all of your commits are atomic. Larger changes should have commits with more detailed information on what changed, any impact on existing code, rationales, etc. ## Coding conventions We strive for consistency above all. Reading the small codebase should give you a good idea of the conventions we follow. -* We use `go fmt` before committing anything +* We use `goimports` before committing anything * We aim to document all exported entities * Go files are broken up into logical functional components * General functions are extracted into modules when possible +### Import Groups + +We aim for two import groups: + +* Standard library imports +* Everything else + +`goimports` already does this for you along with running `go fmt`. + ## Design conventions We maintain a few high-level design principles in all decisions we make. Keep these in mind while devising new functionality: * Updates should be backwards compatible or provide a seamless migration path from *any* previous version * Each subcommand should perform one action and do it well * Each subcommand will ideally work well in a script * Avoid clever functionality and assume each function will be used in ways we didn't imagine diff --git a/GUIDE.md b/GUIDE.md index 07b308f..864ae45 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -1,107 +1,143 @@ # Write.as CLI User Guide The Write.as Command-Line Interface (CLI) is a cross-platform tool for publishing text to [Write.as](https://write.as) and its other sites, like [Paste.as](https://paste.as). It is designed to be simple, scriptable, do one job (publishing) well, and work as you'd expect with other command-line tools. Write.as is a text-publishing service that protects your privacy. There's no sign up required to publish, but if you do sign up, you can access posts across devices and compile collections of them in what most people would call a "blog". -**Note** accounts are not supported in CLI v1.0. They'll be available in [v2.0](https://github.com/writeas/writeas-cli/milestone/4). - ## Uses These are a few common uses for `writeas`. If you get stuck or want to know more, run `writeas [command] --help`. If you still have questions, [ask us](https://write.as/contact). ### Overview ``` -writeas [global options] command [command options] [arguments...] + writeas [global options] command [command options] [arguments...] COMMANDS: - post Alias for default action: create post from stdin - new Compose a new post from the command-line and publish - delete Delete a post - update Update (overwrite) a post - get Read a raw post - add Add an existing post locally - list List local posts - help, h Shows a list of commands or help for one command - + post Alias for default action: create post from stdin + new Compose a new post from the command-line and publish + publish Publish a file to Write.as + delete Delete a post + update Update (overwrite) a post + get Read a raw post + add Add an existing post locally + posts List all of your posts + claim Claim local unsynced posts + blogs List blogs + auth Authenticate with Write.as + logout Log out of Write.as + help, h Shows a list of commands or help for one command + GLOBAL OPTIONS: - --tor, -t Perform action on Tor hidden service - --tor-port "9150" Use a different port to connect to Tor - --code Specifies this post is code - --verbose, -v Make the operation more talkative - --font value Sets post font to given value (default: "mono") - --help, -h show help - --version, -v print the version + -c value, -b value Optional blog to post to + --tor, -t Perform action on Tor hidden service + --tor-port value Use a different port to connect to Tor (default: 9150) + --code Specifies this post is code + --md Returns post URL with Markdown enabled + --verbose, -v Make the operation more talkative + --font value Sets post font to given value (default: "mono") + --lang value Sets post language to given ISO 639-1 language code + --user-agent value Sets the User-Agent for API requests + --help, -h show help + --version, -V print the version ``` #### Share something By default, `writeas` creates a post with a `monospace` typeface that doesn't word wrap (scrolls horizontally). It will return a single line with a URL, and automatically copy that URL to the clipboard: ```bash $ echo "Hello world!" | writeas -https://write.as/aaaaaaaaaaaa +https://write.as/aaaazzzzzzzza ``` This is generally more useful for posting terminal output or code, like so (the `--code` flag turns on syntax highlighting): macOS / Linux: `cat writeas/cli.go | writeas --code` Windows: `type writeas/cli.go | writeas.exe --code` #### Output a post This outputs any Write.as post with the given ID. ```bash -$ writeas get aaaaaaaaaaaa +$ writeas get aaaazzzzzzzza Hello world! ``` +#### Authenticate + +This will authenticate with write.as and store the user access token locally, until you explicitly logout. +```bash +$ writeas auth username +Password: ************ +``` + +#### List all blogs + +This will output a list of the authenticated user's blogs. +```bash +$ writeas blogs +Alias Title +user An Example Blog +dev My Dev Log +``` + #### List all published posts -This lists all posts you've published from your device. +This lists all posts you've published from your device, as well as any published by the authenticated user. Pass the `--url` flag to show the list with full post URLs, and the `--md` flag to return URLs with Markdown enabled. ```bash -$ writeas list -aaaaaaaaaaaa +$ writeas posts +Local ID Token +unsynced aaaazzzzzzzza dhuieoj23894jhf984hdfs9834hdf84j + +Account ID Title +synced mmmmmmmm33333333 This is a post ``` #### Delete a post This permanently deletes a post you own. ```bash -$ writeas delete aaaaaaaaaaaa +$ writeas delete aaaazzzzzzzza ``` #### Update a post This completely overwrites an existing post you own. ```bash -$ echo "See you later!" | writeas update aaaaaaaaaaaa +$ echo "See you later!" | writeas update aaaazzzzzzzza +``` + +#### Claim a post + +This moves an unsynced local post to a draft on your account. You will need to authenticate first. +```bash +$ writeas claim aaaazzzzzzzza ``` ### Composing posts If you simply have a penchant for never leaving your keyboard, `writeas` is great for composing new posts from the command-line. Just use the `new` subcommand. `writeas new` will open your favorite command-line editor, as specified by your `WRITEAS_EDITOR` or `EDITOR` environment variables (in that order), falling back to `vim` on OS X / *nix. Customize your post's appearance with the `--font` flag: | Argument | Appearance (Typeface) | Word Wrap? | | -------- | --------------------- | ---------- | | `sans` | Sans-serif (Open Sans) | Yes | | `serif` | Serif (Lora) | Yes | | `wrap` | Monospace | Yes | | `mono` | Monospace | No | | `code` | Syntax-highlighted monospace | No | Put it all together, e.g. publish with a sans-serif font: `writeas new --font sans` If you're publishing Markdown, supply the `--md` flag to get a URL back that will render Markdown, e.g.: `writeas new --font sans --md` diff --git a/LICENSE b/LICENSE index 7371932..f288702 100644 --- a/LICENSE +++ b/LICENSE @@ -1,22 +1,674 @@ -The MIT License (MIT) + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 -Copyright (c) 2015 Write.as + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: + Preamble -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. + The GNU General Public License is a free, copyleft license for +software and other kinds of works. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU 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. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index fdebb13..65841f4 100644 --- a/README.md +++ b/README.md @@ -1,97 +1,109 @@ writeas-cli =========== -![MIT license](https://img.shields.io/github/license/writeas/writeas-cli.svg) [![Go Report Card](https://goreportcard.com/badge/github.com/writeas/writeas-cli)](https://goreportcard.com/report/github.com/writeas/writeas-cli) [![#writeas on freenode](https://img.shields.io/badge/freenode-%23writeas-blue.svg)](http://webchat.freenode.net/?channels=writeas) [![Public Slack discussion](http://slack.write.as/badge.svg)](http://slack.write.as/) +![GPL](https://img.shields.io/github/license/writeas/writeas-cli.svg) [![Go Report Card](https://goreportcard.com/badge/github.com/writeas/writeas-cli)](https://goreportcard.com/report/github.com/writeas/writeas-cli) [![#writeas on freenode](https://img.shields.io/badge/freenode-%23writeas-blue.svg)](http://webchat.freenode.net/?channels=writeas) [![Discuss on our forum](https://img.shields.io/discourse/https/discuss.write.as/users.svg?label=forum)](https://discuss.write.as/c/development) Command line interface for [Write.as](https://write.as). Works on Windows, macOS, and Linux. +**NOTE: the `master` branch is currently unstable while we prepare the v2.0 release! You should install via official release channel, or build from the `v1.2` tag.** + ## Features * Publish anonymously to Write.as -* A stable, easy back-end for your GUI app or desktop-based workflow +* Authenticate with a Write.as account +* A stable, easy back-end for your [GUI app](https://write.as/apps/desktop) or desktop-based workflow * Compatible with our [Tor hidden service](http://writeas7pm7rcdqg.onion/) * Locally keeps track of any posts you make -* Update and delete anonymous posts +* Update and delete posts, anonymous and authenticated * Fetch any post by ID * Add anonymous post credentials (like for one published with the [Android app](https://play.google.com/store/apps/details?id=com.abunchtell.writeas)) for editing ## Installing The easiest way to get the CLI is to download a pre-built executable for your OS. ### Download [![Latest release](https://img.shields.io/github/release/writeas/writeas-cli.svg)](https://github.com/writeas/writeas-cli/releases/latest) ![Total downloads](https://img.shields.io/github/downloads/writeas/writeas-cli/total.svg) Get the latest version for your operating system as a standalone executable. **Windows**
Download the [64-bit](https://github.com/writeas/writeas-cli/releases/download/v1.2/writeas_1.2_windows_amd64.zip) or [32-bit](https://github.com/writeas/writeas-cli/releases/download/v1.2/writeas_1.2_windows_386.zip) executable and put it somewhere in your `%PATH%`. **macOS**
Download the [64-bit](https://github.com/writeas/writeas-cli/releases/download/v1.2/writeas_1.2_darwin_amd64.tar.gz) executable and put it somewhere in your `$PATH`, like `/usr/local/bin`. **Debian-based Linux**
```bash sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys DBE07445 sudo add-apt-repository "deb http://updates.writeas.org xenial main" sudo apt-get update && sudo apt-get install writeas-cli ``` **Linux (other)**
Download the [64-bit](https://github.com/writeas/writeas-cli/releases/download/v1.2/writeas_1.2_linux_amd64.tar.gz) or [32-bit](https://github.com/writeas/writeas-cli/releases/download/v1.2/writeas_1.2_linux_386.tar.gz) executable and put it somewhere in your `$PATH`, like `/usr/local/bin`. ### Go get it ```bash go get github.com/writeas/writeas-cli/cmd/writeas ``` Once this finishes, you'll see `writeas` or `writeas.exe` inside `$GOPATH/bin/`. ## Upgrading To upgrade the CLI, download and replace the executable you downloaded before. If you previously installed with `go get`, run it again with the `-u` option. ```bash go get -u github.com/writeas/writeas-cli/cmd/writeas ``` ## Usage See full usage documentation on our [User Guide](GUIDE.md). ``` -writeas [global options] command [command options] [arguments...] + writeas [global options] command [command options] [arguments...] COMMANDS: - post Alias for default action: create post from stdin - new Compose a new post from the command-line and publish - delete Delete a post - update Update (overwrite) a post - get Read a raw post - add Add an existing post locally - list List local posts - help, h Shows a list of commands or help for one command - + post Alias for default action: create post from stdin + new Compose a new post from the command-line and publish + publish Publish a file to Write.as + delete Delete a post + update Update (overwrite) a post + get Read a raw post + add Add an existing post locally + posts List all of your posts + blogs List blogs + claim Claim local unsynced posts + auth Authenticate with Write.as + logout Log out of Write.as + help, h Shows a list of commands or help for one command + GLOBAL OPTIONS: - --tor, -t Perform action on Tor hidden service - --tor-port "9150" Use a different port to connect to Tor - --code Specifies this post is code - --verbose, -v Make the operation more talkative - --font value Sets post font to given value (default: "mono") - --help, -h show help - --version, -v print the version + -c value, -b value Optional blog to post to + --tor, -t Perform action on Tor hidden service + --tor-port value Use a different port to connect to Tor (default: 9150) + --code Specifies this post is code + --md Returns post URL with Markdown enabled + --verbose, -v Make the operation more talkative + --font value Sets post font to given value (default: "mono") + --lang value Sets post language to given ISO 639-1 language code + --user-agent value Sets the User-Agent for API requests + --help, -h show help + --version, -V print the version ``` ## Contributing to the CLI For a complete guide to contributing, see the [Contribution Guide](.github/CONTRIBUTING.md). We welcome any kind of contributions including documentation, organizational improvements, tutorials, bug reports, feature requests, new features, answering questions, etc. ### Getting Support -We're available on [several channels](https://write.as/contact), and prefer the #development channel [in Slack](http://slack.write.as) for project discussion. Please don't use the GitHub issue tracker to ask questions. +We're available on [several channels](https://write.as/contact), and prefer our [forum](https://discuss.write.as) for project discussion. Please don't use the GitHub issue tracker to ask questions. ### Reporting Issues If you believe you have found a bug in the CLI or its documentation, file an issue on this repo. If you're not sure if it's a bug or not, [reach out to us](https://write.as/contact) in one way or another. Be sure to provide the version of the CLI (with `writeas --version`) in your report. diff --git a/api/api.go b/api/api.go new file mode 100644 index 0000000..d3fa3fc --- /dev/null +++ b/api/api.go @@ -0,0 +1,267 @@ +package api + +import ( + "fmt" + "path/filepath" + + "github.com/atotto/clipboard" + writeas "github.com/writeas/go-writeas/v2" + "github.com/writeas/web-core/posts" + "github.com/writeas/writeas-cli/config" + "github.com/writeas/writeas-cli/fileutils" + "github.com/writeas/writeas-cli/log" + cli "gopkg.in/urfave/cli.v1" +) + +func client(userAgent string, tor bool) *writeas.Client { + var client *writeas.Client + if tor { + client = writeas.NewTorClient(TorPort) + } else { + if config.IsDev() { + client = writeas.NewDevClient() + } else { + client = writeas.NewClient() + } + } + client.UserAgent = userAgent + + return client +} + +func NewClient(c *cli.Context, authRequired bool) (*writeas.Client, error) { + var client *writeas.Client + if config.IsTor(c) { + client = writeas.NewTorClient(TorPort) + } else { + if config.IsDev() { + client = writeas.NewDevClient() + } else { + client = writeas.NewClient() + } + } + client.UserAgent = config.UserAgent(c) + // TODO: load user into var shared across the app + u, _ := config.LoadUser(config.UserDataDir(c.App.ExtraInfo()["configDir"])) + if u != nil { + client.SetToken(u.AccessToken) + } else if authRequired { + return nil, fmt.Errorf("Not currently logged in. Authenticate with: writeas auth ") + } + + return client, nil +} + +// DoFetch retrieves the Write.as post with the given friendlyID, +// optionally via the Tor hidden service. +func DoFetch(friendlyID, ua string, tor bool) error { + cl := client(ua, tor) + + p, err := cl.GetPost(friendlyID) + if err != nil { + return err + } + + if p.Title != "" { + fmt.Printf("# %s\n\n", string(p.Title)) + } + fmt.Printf("%s\n", string(p.Content)) + return nil +} + +// DoFetchPosts retrieves all remote posts for the +// authenticated user +func DoFetchPosts(c *cli.Context) ([]writeas.Post, error) { + cl, err := NewClient(c, true) + if err != nil { + return nil, err + } + + posts, err := cl.GetUserPosts() + if err != nil { + return nil, err + } + + return *posts, nil +} + +// DoPost creates a Write.as post, returning an error if it was +// unsuccessful. +func DoPost(c *cli.Context, post []byte, font string, encrypt, tor, code bool) (*writeas.Post, error) { + cl, _ := NewClient(c, false) + + pp := &writeas.PostParams{ + Font: config.GetFont(code, font), + Collection: config.Collection(c), + } + pp.Title, pp.Content = posts.ExtractTitle(string(post)) + if lang := config.Language(c, true); lang != "" { + pp.Language = &lang + } + p, err := cl.CreatePost(pp) + if err != nil { + return nil, fmt.Errorf("Unable to post: %v", err) + } + + var url string + if p.Collection != nil { + url = p.Collection.URL + p.Slug + } else { + if tor { + url = config.TorBaseURL + } else if config.IsDev() { + url = config.DevBaseURL + } else { + url = config.WriteasBaseURL + } + url += "/" + p.ID + // Output URL in requested format + if c.Bool("md") { + url += ".md" + } + } + + if cl.Token() == "" { + // Store post locally, since we're not authenticated + AddPost(c, p.ID, p.Token) + } + + // Copy URL to clipboard + err = clipboard.WriteAll(string(url)) + if err != nil { + log.Errorln("writeas: Didn't copy to clipboard: %s", err) + } else { + log.Info(c, "Copied to clipboard.") + } + + // Output URL + fmt.Printf("%s\n", url) + + return p, nil +} + +// DoFetchCollections retrieves a list of the currently logged in users +// collections. +func DoFetchCollections(c *cli.Context) ([]RemoteColl, error) { + cl, err := NewClient(c, true) + if err != nil { + if config.Debug() { + log.ErrorlnQuit("could not create new client: %v", err) + } + return nil, fmt.Errorf("Couldn't create new client") + } + + colls, err := cl.GetUserCollections() + if err != nil { + if config.Debug() { + log.ErrorlnQuit("failed fetching user collections: %v", err) + } + return nil, fmt.Errorf("Couldn't get user collections") + } + + out := make([]RemoteColl, len(*colls)) + + for i, c := range *colls { + coll := RemoteColl{ + Alias: c.Alias, + Title: c.Title, + URL: c.URL, + } + out[i] = coll + } + + return out, nil +} + +// DoUpdate updates the given post on Write.as. +func DoUpdate(c *cli.Context, post []byte, friendlyID, token, font string, tor, code bool) error { + cl, _ := NewClient(c, false) + + params := writeas.PostParams{} + params.Title, params.Content = posts.ExtractTitle(string(post)) + if lang := config.Language(c, false); lang != "" { + params.Language = &lang + } + if code || font != "" { + params.Font = config.GetFont(code, font) + } + + _, err := cl.UpdatePost(friendlyID, token, ¶ms) + if err != nil { + if config.Debug() { + log.ErrorlnQuit("Problem updating: %v", err) + } + return fmt.Errorf("Post doesn't exist, or bad edit token given.") + } + + if tor { + log.Info(c, "Post updated via hidden service.") + } else { + log.Info(c, "Post updated.") + } + return nil +} + +// DoDelete deletes the given post on Write.as, and removes any local references +func DoDelete(c *cli.Context, friendlyID, token string, tor bool) error { + cl, _ := NewClient(c, false) + + err := cl.DeletePost(friendlyID, token) + if err != nil { + if config.Debug() { + log.ErrorlnQuit("Problem deleting: %v", err) + } + return fmt.Errorf("Post doesn't exist, or bad edit token given.") + } + + if tor { + log.Info(c, "Post deleted from hidden service.") + } else { + log.Info(c, "Post deleted.") + } + RemovePost(c.App.ExtraInfo()["configDir"], friendlyID) + + return nil +} + +func DoLogIn(c *cli.Context, username, password string) error { + cl := client(config.UserAgent(c), config.IsTor(c)) + + u, err := cl.LogIn(username, password) + if err != nil { + if config.Debug() { + log.ErrorlnQuit("Problem logging in: %v", err) + } + return err + } + + err = config.SaveUser(config.UserDataDir(c.App.ExtraInfo()["configDir"]), u) + if err != nil { + return err + } + log.Info(c, "Logged in as %s.\n", u.User.Username) + return nil +} + +func DoLogOut(c *cli.Context) error { + cl, err := NewClient(c, true) + if err != nil { + return err + } + + err = cl.LogOut() + if err != nil { + if config.Debug() { + log.ErrorlnQuit("Problem logging out: %v", err) + } + return err + } + + // Delete local user data + err = fileutils.DeleteFile(filepath.Join(config.UserDataDir(c.App.ExtraInfo()["configDir"]), config.UserFile)) + if err != nil { + return err + } + + return nil +} diff --git a/api/collections.go b/api/collections.go new file mode 100644 index 0000000..a7483b1 --- /dev/null +++ b/api/collections.go @@ -0,0 +1,9 @@ +package api + +// RemoteColl represents a collection of posts +// It is a reduced set of data from a go-writeas Collection +type RemoteColl struct { + Alias string + Title string + URL string +} diff --git a/api/posts.go b/api/posts.go new file mode 100644 index 0000000..379a2c6 --- /dev/null +++ b/api/posts.go @@ -0,0 +1,304 @@ +package api + +import ( + "bufio" + "fmt" + "io" + "io/ioutil" + "os" + "path/filepath" + "strings" + "time" + + writeas "github.com/writeas/go-writeas/v2" + "github.com/writeas/writeas-cli/config" + "github.com/writeas/writeas-cli/fileutils" + "github.com/writeas/writeas-cli/log" + cli "gopkg.in/urfave/cli.v1" +) + +const ( + postsFile = "posts.psv" + separator = `|` +) + +// Post holds the basic authentication information for a Write.as post. +type Post struct { + ID string + EditToken string +} + +// RemotePost holds addition information about published +// posts +type RemotePost struct { + Post + Title, + Excerpt, + Slug, + Collection, + EditToken string + Synced bool + Updated time.Time +} + +func AddPost(c *cli.Context, id, token string) error { + f, err := os.OpenFile(filepath.Join(config.UserDataDir(c.App.ExtraInfo()["configDir"]), postsFile), os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600) + if err != nil { + return fmt.Errorf("Error creating local posts list: %s", err) + } + defer f.Close() + + l := fmt.Sprintf("%s%s%s\n", id, separator, token) + + if _, err = f.WriteString(l); err != nil { + return fmt.Errorf("Error writing to local posts list: %s", err) + } + + return nil +} + +// ClaimPost adds a local post to the authenticated user's account and deletes +// the local reference +func ClaimPosts(c *cli.Context, localPosts *[]Post) (*[]writeas.ClaimPostResult, error) { + cl, err := NewClient(c, true) + if err != nil { + return nil, err + } + postsToClaim := make([]writeas.OwnedPostParams, len(*localPosts)) + for i, post := range *localPosts { + postsToClaim[i] = writeas.OwnedPostParams{ + ID: post.ID, + Token: post.EditToken, + } + } + + return cl.ClaimPosts(&postsToClaim) +} + +func TokenFromID(c *cli.Context, id string) string { + post := fileutils.FindLine(filepath.Join(config.UserDataDir(c.App.ExtraInfo()["configDir"]), postsFile), id) + if post == "" { + return "" + } + + parts := strings.Split(post, separator) + if len(parts) < 2 { + return "" + } + + return parts[1] +} + +func RemovePost(path, id string) { + fileutils.RemoveLine(filepath.Join(config.UserDataDir(path), postsFile), id) +} + +func GetPosts(c *cli.Context) *[]Post { + lines := fileutils.ReadData(filepath.Join(config.UserDataDir(c.App.ExtraInfo()["configDir"]), postsFile)) + + posts := []Post{} + + if lines != nil && len(*lines) > 0 { + parts := make([]string, 2) + for _, l := range *lines { + parts = strings.Split(l, separator) + if len(parts) < 2 { + continue + } + posts = append(posts, Post{ID: parts[0], EditToken: parts[1]}) + } + } + + return &posts +} + +func GetUserPosts(c *cli.Context) ([]RemotePost, error) { + waposts, err := DoFetchPosts(c) + if err != nil { + return nil, err + } + + if len(waposts) == 0 { + return nil, nil + } + + posts := []RemotePost{} + for _, p := range waposts { + post := RemotePost{ + Post: Post{ + ID: p.ID, + EditToken: p.Token, + }, + Title: p.Title, + Excerpt: getExcerpt(p.Content), + Slug: p.Slug, + Synced: p.Slug != "", + Updated: p.Updated, + } + if p.Collection != nil { + post.Collection = p.Collection.Alias + } + posts = append(posts, post) + } + + return posts, nil +} + +// getExcerpt takes in a content string and returns +// a concatenated version. limited to no more than +// two lines of 80 chars each. delimited by '...' +func getExcerpt(input string) string { + length := len(input) + + if length <= 80 { + return input + } else if length < 160 { + ln1, idx := trimToLength(input, 80) + if idx == -1 { + idx = 80 + } + ln2, _ := trimToLength(input[idx:], 80) + return ln1 + "\n" + ln2 + } else { + excerpt := input[:158] + ln1, idx := trimToLength(excerpt, 80) + if idx == -1 { + idx = 80 + } + ln2, _ := trimToLength(excerpt[idx:], 80) + return ln1 + "\n" + ln2 + "..." + } +} + +func trimToLength(in string, l int) (string, int) { + c := []rune(in) + spaceIdx := -1 + length := len(c) + if length <= l { + return in, spaceIdx + } + + for i := l; i > 0; i-- { + if c[i] == ' ' { + spaceIdx = i + break + } + } + if spaceIdx > -1 { + c = c[:spaceIdx] + } + return string(c), spaceIdx +} + +func ComposeNewPost() (string, *[]byte) { + f, err := fileutils.TempFile(os.TempDir(), "WApost", "txt") + if err != nil { + if config.Debug() { + panic(err) + } else { + log.Errorln("Error creating temp file: %s", err) + return "", nil + } + } + f.Close() + + cmd := config.EditPostCmd(f.Name()) + if cmd == nil { + os.Remove(f.Name()) + + fmt.Println(config.NoEditorErr) + return "", nil + } + cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr + if err := cmd.Start(); err != nil { + os.Remove(f.Name()) + + if config.Debug() { + panic(err) + } else { + log.Errorln("Error starting editor: %s", err) + return "", nil + } + } + + // If something fails past this point, the temporary post file won't be + // removed automatically. Calling function should handle this. + if err := cmd.Wait(); err != nil { + if config.Debug() { + panic(err) + } else { + log.Errorln("Editor finished with error: %s", err) + return "", nil + } + } + + post, err := ioutil.ReadFile(f.Name()) + if err != nil { + if config.Debug() { + panic(err) + } else { + log.Errorln("Error reading post: %s", err) + return "", nil + } + } + return f.Name(), &post +} + +func WritePost(postsDir string, p *writeas.Post) error { + postFilename := p.ID + collDir := "" + if p.Collection != nil { + postFilename = p.Slug + collDir = p.Collection.Alias + } + postFilename += PostFileExt + + txtFile := p.Content + if p.Title != "" { + txtFile = "# " + p.Title + "\n\n" + txtFile + } + return ioutil.WriteFile(filepath.Join(postsDir, collDir, postFilename), []byte(txtFile), 0644) +} + +func HandlePost(fullPost []byte, c *cli.Context) (*writeas.Post, error) { + tor := config.IsTor(c) + if c.Int("tor-port") != 0 { + TorPort = c.Int("tor-port") + } + if tor { + log.Info(c, "Posting to hidden service...") + } else { + log.Info(c, "Posting...") + } + + return DoPost(c, fullPost, c.String("font"), false, tor, c.Bool("code")) +} + +func ReadStdIn() []byte { + numBytes, numChunks := int64(0), int64(0) + r := bufio.NewReader(os.Stdin) + fullPost := []byte{} + buf := make([]byte, 0, 1024) + for { + n, err := r.Read(buf[:cap(buf)]) + buf = buf[:n] + if n == 0 { + if err == nil { + continue + } + if err == io.EOF { + break + } + log.ErrorlnQuit("Error reading from stdin: %v", err) + } + numChunks++ + numBytes += int64(len(buf)) + + fullPost = append(fullPost, buf...) + if err != nil && err != io.EOF { + log.ErrorlnQuit("Error appending to end of post: %v", err) + } + } + + return fullPost +} diff --git a/api/posts_test.go b/api/posts_test.go new file mode 100644 index 0000000..8630efe --- /dev/null +++ b/api/posts_test.go @@ -0,0 +1,103 @@ +package api + +import "testing" + +func TestTrimToLength(t *testing.T) { + tt := []struct { + Name string + Data string + Length int + ResultData string + ResultIDX int + }{ + { + "English, longer than trim length", + "This is a string, let's truncate it.", + 12, + "This is a", + 9, + }, { + "English, equal to length", + "Some other string.", + 18, + "Some other string.", + -1, + }, { + "English, shorter than trim length", + "I'm short!", + 20, + "I'm short!", + -1, + }, { + "Multi-byte, longer than trim length", + "這是一個較長的廣東話。 有許多特性可以確保足夠長的輸出。", + 14, + "這是一個較長的廣東話。", + 11, + }, { + "Multi-byte, equal to length", + "這是一個簡短的廣東話。", + 11, + "這是一個簡短的廣東話。", + -1, + }, { + "Multi-byte, shorter than trim length", + "我也很矮! 有空間。", + 20, + "我也很矮! 有空間。", + -1, + }, + } + + for _, tc := range tt { + t.Run(tc.Name, func(t *testing.T) { + out, idx := trimToLength(tc.Data, tc.Length) + if out != tc.ResultData { + t.Errorf("Incorrect output, expecting \"%s\" but got \"%s\"", tc.ResultData, out) + } + + if idx != tc.ResultIDX { + t.Errorf("Incorrect last index, expected \"%d\" but got \"%d\"", tc.ResultIDX, idx) + } + }) + } +} + +func TestGetExcerpt(t *testing.T) { + tt := []struct { + Name string + Data string + Result string + }{ + { + "Shorter than one line", + "This is much less than 80 chars", + "This is much less than 80 chars", + }, { + "Exact length, one line", + "This will be only 80 chars. Maybe all the way to column 88, that will do it. ---", + "This will be only 80 chars. Maybe all the way to column 88, that will do it. ---", + }, { + "Shorter than two lines", + "This will be more than one line but shorter than two. It should break at the 80th or less character. Let's check it out.", + "This will be more than one line but shorter than two. It should break at the\n 80th or less character. Let's check it out.", + }, { + "Exact length, two lines", + "This should be the exact length for two lines. There should ideally be no trailing periods to indicate further text. However trimToLength breaks on word bounds.", + "This should be the exact length for two lines. There should ideally be no\n trailing periods to indicate further text. However trimToLength breaks on word...", + }, { + "Longer than two lines", + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque volutpat sagittis aliquet. Ut eu rutrum nisl. Proin molestie ante in dui vulputate dictum. Proin ac bibendum eros. Nulla porta congue tellus, sed vehicula sem bibendum eu. Donec vehicula erat viverra fermentum mattis. Integer volutpat.", + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque volutpat\n sagittis aliquet. Ut eu rutrum nisl. Proin molestie ante in dui vulputate...", + }, + } + + for _, tc := range tt { + t.Run(tc.Name, func(t *testing.T) { + out := getExcerpt(tc.Data) + if out != tc.Result { + t.Errorf("Output does not match:\nexpected \"%s\"\nbut got \"%s\"", tc.Result, out) + } + }) + } +} diff --git a/api/sync.go b/api/sync.go new file mode 100644 index 0000000..d687f24 --- /dev/null +++ b/api/sync.go @@ -0,0 +1,131 @@ +package api + +import ( + //"github.com/writeas/writeas-cli/sync" + "fmt" + "io/ioutil" + "os" + "path/filepath" + + "github.com/writeas/writeas-cli/config" + "github.com/writeas/writeas-cli/fileutils" + "github.com/writeas/writeas-cli/log" + cli "gopkg.in/urfave/cli.v1" +) + +const ( + PostFileExt = ".txt" + userFilename = "writeas_user" +) + +func CmdPull(c *cli.Context) error { + cfg, err := config.LoadConfig(config.UserDataDir(c.App.ExtraInfo()["configDir"])) + if err != nil { + return err + } + // Create posts directory if needed + if cfg.Posts.Directory == "" { + syncSetUp(c.App.ExtraInfo()["configDir"], cfg) + } + + // Fetch posts + cl, err := NewClient(c, true) + if err != nil { + return err + } + + posts, err := cl.GetUserPosts() + if err != nil { + return err + } + + for _, p := range *posts { + postFilename := p.ID + collDir := "" + if p.Collection != nil { + postFilename = p.Slug + // Create directory for collection + collDir = p.Collection.Alias + if !fileutils.Exists(filepath.Join(cfg.Posts.Directory, collDir)) { + log.Info(c, "Creating folder "+collDir) + err = os.Mkdir(filepath.Join(cfg.Posts.Directory, collDir), 0755) + if err != nil { + log.Errorln("Error creating blog directory %s: %s. Skipping post %s.", collDir, err, postFilename) + continue + } + } + } + postFilename += PostFileExt + + // Write file + txtFile := p.Content + if p.Title != "" { + txtFile = "# " + p.Title + "\n\n" + txtFile + } + err = ioutil.WriteFile(filepath.Join(cfg.Posts.Directory, collDir, postFilename), []byte(txtFile), 0644) + if err != nil { + log.Errorln("Error creating file %s: %s", postFilename, err) + } + log.Info(c, "Saved post "+postFilename) + + // Update mtime and atime on files + modTime := p.Updated.Local() + err = os.Chtimes(filepath.Join(cfg.Posts.Directory, collDir, postFilename), modTime, modTime) + if err != nil { + log.Errorln("Error setting time on %s: %s", postFilename, err) + } + } + + return nil +} + +func syncSetUp(path string, cfg *config.UserConfig) error { + // Get user information and fail early (before we make the user do + // anything), if we're going to + u, err := config.LoadUser(config.UserDataDir(path)) + if err != nil { + return err + } + + // Prompt for posts directory + defaultDir, err := os.Getwd() + if err != nil { + return err + } + var dir string + fmt.Printf("Posts directory? [%s]: ", defaultDir) + fmt.Scanln(&dir) + if dir == "" { + dir = defaultDir + } + + // FIXME: This only works on non-Windows OSes (fix: https://www.reddit.com/r/golang/comments/5t3ezd/hidden_files_directories/) + userFilepath := filepath.Join(dir, "."+userFilename) + + // Create directory if needed + if !fileutils.Exists(dir) { + err = os.MkdirAll(dir, 0700) + if err != nil { + if config.Debug() { + log.Errorln("Error creating data directory: %s", err) + } + return err + } + // Create username file in directory + err = ioutil.WriteFile(userFilepath, []byte(u.User.Username), 0644) + fmt.Println("Created posts directory.") + } + + // Save preference + cfg.Posts.Directory = dir + err = config.SaveConfig(config.UserDataDir(path), cfg) + if err != nil { + if config.Debug() { + log.Errorln("Unable to save config: %s", err) + } + return err + } + fmt.Println("Saved config.") + + return nil +} diff --git a/cmd/writeas/tor.go b/api/tor.go similarity index 81% rename from cmd/writeas/tor.go rename to api/tor.go index 00f1821..dae5be5 100644 --- a/cmd/writeas/tor.go +++ b/api/tor.go @@ -1,17 +1,18 @@ -package main +package api import ( - "code.as/core/socks" "fmt" "net/http" + + "code.as/core/socks" ) var ( - torPort = 9150 + TorPort = 9150 ) func torClient() *http.Client { - dialSocksProxy := socks.DialSocksProxy(socks.SOCKS5, fmt.Sprintf("127.0.0.1:%d", torPort)) + dialSocksProxy := socks.DialSocksProxy(socks.SOCKS5, fmt.Sprintf("127.0.0.1:%d", TorPort)) transport := &http.Transport{Dial: dialSocksProxy} return &http.Client{Transport: transport} } diff --git a/cmd/writeas/api.go b/cmd/writeas/api.go deleted file mode 100644 index 1f441da..0000000 --- a/cmd/writeas/api.go +++ /dev/null @@ -1,205 +0,0 @@ -package main - -import ( - "bytes" - "fmt" - "github.com/atotto/clipboard" - "gopkg.in/urfave/cli.v1" - "io/ioutil" - "net/http" - "net/url" - "strconv" - "strings" -) - -const ( - defaultUserAgent = "writeas-cli v" + version -) - -func userAgent(c *cli.Context) string { - ua := c.String("user-agent") - if ua == "" { - return defaultUserAgent - } - return ua + " (" + defaultUserAgent + ")" -} - -func client(read, tor bool, path, query string) (string, *http.Client) { - var u *url.URL - var client *http.Client - if tor { - u, _ = url.ParseRequestURI(hiddenAPIURL) - u.Path = "/api/" + path - client = torClient() - } else { - u, _ = url.ParseRequestURI(apiURL) - u.Path = "/api/" + path - client = &http.Client{} - } - if query != "" { - u.RawQuery = query - } - urlStr := fmt.Sprintf("%v", u) - - return urlStr, client -} - -// DoFetch retrieves the Write.as post with the given friendlyID, -// optionally via the Tor hidden service. -func DoFetch(friendlyID, ua string, tor bool) error { - path := friendlyID - - urlStr, client := client(true, tor, path, "") - - r, _ := http.NewRequest("GET", urlStr, nil) - r.Header.Add("User-Agent", ua) - - resp, err := client.Do(r) - if err != nil { - return err - } - defer resp.Body.Close() - - if resp.StatusCode == http.StatusOK { - content, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - fmt.Printf("%s\n", string(content)) - } else if resp.StatusCode == http.StatusNotFound { - return ErrPostNotFound - } else if resp.StatusCode == http.StatusGone { - } else { - return fmt.Errorf("Unable to get post: %s", resp.Status) - } - return nil -} - -// DoPost creates a Write.as post, returning an error if it was -// unsuccessful. -func DoPost(c *cli.Context, post []byte, font string, encrypt, tor, code bool) error { - data := url.Values{} - data.Set("w", string(post)) - if encrypt { - data.Add("e", "") - } - data.Add("font", getFont(code, font)) - - urlStr, client := client(false, tor, "", "") - - r, _ := http.NewRequest("POST", urlStr, bytes.NewBufferString(data.Encode())) - r.Header.Add("User-Agent", userAgent(c)) - r.Header.Add("Content-Type", "application/x-www-form-urlencoded") - r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode()))) - - resp, err := client.Do(r) - if err != nil { - return err - } - defer resp.Body.Close() - - if resp.StatusCode == http.StatusOK { - content, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - - nlPos := strings.Index(string(content), "\n") - url := content[:nlPos] - idPos := strings.LastIndex(string(url), "/") + 1 - id := string(url[idPos:]) - token := string(content[nlPos+1 : len(content)-1]) - - addPost(id, token) - - // Output URL in requested format - if c.Bool("md") { - url = append(url, []byte(".md")...) - } - // Copy URL to clipboard - err = clipboard.WriteAll(string(url)) - if err != nil { - Errorln("writeas: Didn't copy to clipboard: %s", err) - } else { - Info(c, "Copied to clipboard.") - } - - // Output URL - fmt.Printf("%s\n", url) - } else { - return fmt.Errorf("Unable to post: %s", resp.Status) - } - - return nil -} - -// DoUpdate updates the given post on Write.as. -func DoUpdate(c *cli.Context, post []byte, friendlyID, token, font string, tor, code bool) error { - urlStr, client := client(false, tor, friendlyID, fmt.Sprintf("t=%s", token)) - - data := url.Values{} - data.Set("w", string(post)) - - if code || font != "" { - // Only update font if explicitly changed - data.Add("font", getFont(code, font)) - } - - r, _ := http.NewRequest("POST", urlStr, bytes.NewBufferString(data.Encode())) - r.Header.Add("User-Agent", userAgent(c)) - r.Header.Add("Content-Type", "application/x-www-form-urlencoded") - r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode()))) - - resp, err := client.Do(r) - if err != nil { - return err - } - defer resp.Body.Close() - - if resp.StatusCode == http.StatusOK { - if tor { - Info(c, "Post updated via hidden service.") - } else { - Info(c, "Post updated.") - } - } else { - if debug { - ErrorlnQuit("Problem updating: %s", resp.Status) - } else { - return fmt.Errorf("Post doesn't exist, or bad edit token given.") - } - } - return nil -} - -// DoDelete deletes the given post on Write.as. -func DoDelete(c *cli.Context, friendlyID, token string, tor bool) error { - urlStr, client := client(false, tor, friendlyID, fmt.Sprintf("t=%s", token)) - - r, _ := http.NewRequest("DELETE", urlStr, nil) - r.Header.Add("User-Agent", userAgent(c)) - r.Header.Add("Content-Type", "application/x-www-form-urlencoded") - - resp, err := client.Do(r) - if err != nil { - return err - } - defer resp.Body.Close() - - if resp.StatusCode == http.StatusOK { - if tor { - Info(c, "Post deleted from hidden service.") - } else { - Info(c, "Post deleted.") - } - removePost(friendlyID) - } else { - if debug { - ErrorlnQuit("Problem deleting: %s", resp.Status) - } else { - return fmt.Errorf("Post doesn't exist, or bad edit token given.") - } - } - - return nil -} diff --git a/cmd/writeas/commands.go b/cmd/writeas/commands.go deleted file mode 100644 index f984848..0000000 --- a/cmd/writeas/commands.go +++ /dev/null @@ -1,159 +0,0 @@ -package main - -import ( - "fmt" - "gopkg.in/urfave/cli.v1" - "os" -) - -func cmdPost(c *cli.Context) error { - err := handlePost(readStdIn(), c) - return err -} - -func cmdNew(c *cli.Context) error { - fname, p := composeNewPost() - if p == nil { - // Assume composeNewPost already told us what the error was. Abort now. - os.Exit(1) - } - - // Ensure we have something to post - if len(*p) == 0 { - // Clean up temporary post - if fname != "" { - os.Remove(fname) - } - - InfolnQuit("Empty post. Bye!") - } - - err := handlePost(*p, c) - if err != nil { - Errorln("Error posting: %s", err) - Errorln(messageRetryCompose(fname)) - return cli.NewExitError("", 1) - } - - // Clean up temporary post - if fname != "" { - os.Remove(fname) - } - - return nil -} - -func cmdDelete(c *cli.Context) error { - friendlyID := c.Args().Get(0) - token := c.Args().Get(1) - if friendlyID == "" { - return cli.NewExitError("usage: writeas delete []", 1) - } - - if token == "" { - // Search for the token locally - token = tokenFromID(friendlyID) - if token == "" { - Errorln("Couldn't find an edit token locally. Did you create this post here?") - ErrorlnQuit("If you have an edit token, use: writeas delete %s ", friendlyID) - } - } - - tor := c.Bool("tor") || c.Bool("t") - if c.Int("tor-port") != 0 { - torPort = c.Int("tor-port") - } - if tor { - Info(c, "Deleting via hidden service...") - } else { - Info(c, "Deleting...") - } - - return DoDelete(c, friendlyID, token, tor) -} - -func cmdUpdate(c *cli.Context) error { - friendlyID := c.Args().Get(0) - token := c.Args().Get(1) - if friendlyID == "" { - return cli.NewExitError("usage: writeas update []", 1) - } - - if token == "" { - // Search for the token locally - token = tokenFromID(friendlyID) - if token == "" { - Errorln("Couldn't find an edit token locally. Did you create this post here?") - ErrorlnQuit("If you have an edit token, use: writeas update %s ", friendlyID) - } - } - - // Read post body - fullPost := readStdIn() - - tor := c.Bool("tor") || c.Bool("t") - if c.Int("tor-port") != 0 { - torPort = c.Int("tor-port") - } - if tor { - Info(c, "Updating via hidden service...") - } else { - Info(c, "Updating...") - } - - return DoUpdate(c, fullPost, friendlyID, token, c.String("font"), tor, c.Bool("code")) -} - -func cmdGet(c *cli.Context) error { - friendlyID := c.Args().Get(0) - if friendlyID == "" { - return cli.NewExitError("usage: writeas get ", 1) - } - - tor := c.Bool("tor") || c.Bool("t") - if c.Int("tor-port") != 0 { - torPort = c.Int("tor-port") - } - if tor { - Info(c, "Getting via hidden service...") - } else { - Info(c, "Getting...") - } - - return DoFetch(friendlyID, userAgent(c), tor) -} - -func cmdAdd(c *cli.Context) error { - friendlyID := c.Args().Get(0) - token := c.Args().Get(1) - if friendlyID == "" || token == "" { - return cli.NewExitError("usage: writeas add ", 1) - } - - err := addPost(friendlyID, token) - return err -} - -func cmdList(c *cli.Context) error { - urls := c.Bool("url") - ids := c.Bool("id") - - var p Post - posts := getPosts() - for i := range *posts { - p = (*posts)[len(*posts)-1-i] - if ids || !urls { - fmt.Printf("%s ", p.ID) - } - if urls { - ext := "" - // Output URL in requested format - if c.Bool("md") { - ext = ".md" - } - fmt.Printf("https://write.as/%s%s ", p.ID, ext) - } - fmt.Print("\n") - } - return nil -} diff --git a/cmd/writeas/config.go b/cmd/writeas/config.go deleted file mode 100644 index bf08f2c..0000000 --- a/cmd/writeas/config.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build !debug - -package main - -const ( - debug = false -) diff --git a/cmd/writeas/config_debug.go b/cmd/writeas/config_debug.go deleted file mode 100644 index d51d841..0000000 --- a/cmd/writeas/config_debug.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build debug - -package main - -const ( - debug = true -) diff --git a/cmd/writeas/config_nix.go b/cmd/writeas/config_nix.go new file mode 100644 index 0000000..6b3cb86 --- /dev/null +++ b/cmd/writeas/config_nix.go @@ -0,0 +1,7 @@ +// +build !windows + +package main + +var appInfo = map[string]string{ + "configDir": ".writeas", +} diff --git a/cmd/writeas/config_win.go b/cmd/writeas/config_win.go new file mode 100644 index 0000000..9a7eea1 --- /dev/null +++ b/cmd/writeas/config_win.go @@ -0,0 +1,7 @@ +// +build windows + +package main + +var appInfo = map[string]string{ + "configDir": "Write.as", +} diff --git a/cmd/writeas/edit.go b/cmd/writeas/edit.go deleted file mode 100644 index fdf72b7..0000000 --- a/cmd/writeas/edit.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "os" -) - -var editors = []string{"WRITEAS_EDITOR", "EDITOR"} - -func getConfiguredEditor() string { - for _, v := range editors { - if e := os.Getenv(v); e != "" { - return e - } - } - return "" -} diff --git a/cmd/writeas/cli.go b/cmd/writeas/main.go similarity index 54% rename from cmd/writeas/cli.go rename to cmd/writeas/main.go index 0db42f5..c113d19 100644 --- a/cmd/writeas/cli.go +++ b/cmd/writeas/main.go @@ -1,270 +1,265 @@ package main import ( - "bufio" - "gopkg.in/urfave/cli.v1" - "io" - "log" "os" -) - -// API constants for communicating with Write.as. -const ( - apiURL = "https://write.as" - hiddenAPIURL = "http://writeas7pm7rcdqg.onion" - readAPIURL = "https://write.as" -) - -// Application constants. -const ( - version = "1.2" -) -// Defaults for posts on Write.as. -const ( - defaultFont = PostFontMono + "github.com/writeas/writeas-cli/commands" + "github.com/writeas/writeas-cli/config" + "github.com/writeas/writeas-cli/log" + cli "gopkg.in/urfave/cli.v1" ) -// Available flags for creating posts -var postFlags = []cli.Flag{ - cli.BoolFlag{ - Name: "tor, t", - Usage: "Perform action on Tor hidden service", - }, - cli.IntFlag{ - Name: "tor-port", - Usage: "Use a different port to connect to Tor", - Value: 9150, - }, - cli.BoolFlag{ - Name: "code", - Usage: "Specifies this post is code", - }, - cli.BoolFlag{ - Name: "md", - Usage: "Returns post URL with Markdown enabled", - }, - cli.BoolFlag{ - Name: "verbose, v", - Usage: "Make the operation more talkative", - }, - cli.StringFlag{ - Name: "font", - Usage: "Sets post font to given value", - Value: defaultFont, - }, - cli.StringFlag{ - Name: "user-agent", - Usage: "Sets the User-Agent for API requests", - Value: "", - }, -} - func main() { - initialize() - + initialize(appInfo["configDir"]) cli.VersionFlag = cli.BoolFlag{ Name: "version, V", Usage: "print the version", } // Run the app app := cli.NewApp() app.Name = "writeas" - app.Version = version + app.Version = config.Version app.Usage = "Publish text quickly" app.Authors = []cli.Author{ { Name: "Write.as", Email: "hello@write.as", }, } - app.Action = cmdPost - app.Flags = postFlags + app.ExtraInfo = func() map[string]string { + return appInfo + } + app.Action = commands.CmdPost + app.Flags = config.PostFlags app.Commands = []cli.Command{ { Name: "post", Usage: "Alias for default action: create post from stdin", - Action: cmdPost, - Flags: postFlags, + Action: commands.CmdPost, + Flags: config.PostFlags, Description: `Create a new post on Write.as from stdin. Use the --code flag to indicate that the post should use syntax highlighting. Or use the --font [value] argument to set the post's appearance, where [value] is mono, monospace (default), wrap (monospace font with word wrapping), serif, or sans.`, }, { Name: "new", Usage: "Compose a new post from the command-line and publish", Description: `An alternative to piping data to the program. On Windows, this will use 'copy con' to start reading what you input from the prompt. Press F6 or Ctrl-Z then Enter to end input. On *nix, this will use the best available text editor, starting with the - value set to the WRITAS_EDITOR or EDITOR environment variable, or vim, or + value set to the WRITEAS_EDITOR or EDITOR environment variable, or vim, or finally nano. Use the --code flag to indicate that the post should use syntax highlighting. Or use the --font [value] argument to set the post's appearance, where [value] is mono, monospace (default), wrap (monospace font with word wrapping), serif, or sans. If posting fails for any reason, 'writeas' will show you the temporary file location and how to pipe it to 'writeas' to retry.`, - Action: cmdNew, - Flags: postFlags, + Action: commands.CmdNew, + Flags: config.PostFlags, + }, + { + Name: "publish", + Usage: "Publish a file to Write.as", + Action: commands.CmdPublish, + Flags: config.PostFlags, }, { Name: "delete", Usage: "Delete a post", - Action: cmdDelete, + Action: commands.CmdDelete, Flags: []cli.Flag{ cli.BoolFlag{ Name: "tor, t", Usage: "Delete via Tor hidden service", }, cli.IntFlag{ Name: "tor-port", Usage: "Use a different port to connect to Tor", Value: 9150, }, + cli.BoolFlag{ + Name: "verbose, v", + Usage: "Make the operation more talkative", + }, }, }, { Name: "update", Usage: "Update (overwrite) a post", - Action: cmdUpdate, + Action: commands.CmdUpdate, Flags: []cli.Flag{ cli.BoolFlag{ Name: "tor, t", Usage: "Update via Tor hidden service", }, cli.IntFlag{ Name: "tor-port", Usage: "Use a different port to connect to Tor", Value: 9150, }, cli.BoolFlag{ Name: "code", Usage: "Specifies this post is code", }, cli.StringFlag{ Name: "font", Usage: "Sets post font to given value", }, + cli.BoolFlag{ + Name: "verbose, v", + Usage: "Make the operation more talkative", + }, }, }, { Name: "get", Usage: "Read a raw post", - Action: cmdGet, + Action: commands.CmdGet, Flags: []cli.Flag{ cli.BoolFlag{ Name: "tor, t", Usage: "Get from Tor hidden service", }, cli.IntFlag{ Name: "tor-port", Usage: "Use a different port to connect to Tor", Value: 9150, }, + cli.BoolFlag{ + Name: "verbose, v", + Usage: "Make the operation more talkative", + }, }, }, { Name: "add", Usage: "Add an existing post locally", Description: `A way to add an existing post to your local store for easy editing later. This requires a post ID (from https://write.as/[ID]) and an Edit Token (exported from another Write.as client, such as the Android app). `, - Action: cmdAdd, + Action: commands.CmdAdd, }, { - Name: "list", - Usage: "List local posts", - Action: cmdList, + Name: "posts", + Usage: "List all of your posts", + Description: "This will list only local posts when not currently authenticated. To list remote posts as well, first run: writeas auth .", + Action: commands.CmdListPosts, Flags: []cli.Flag{ cli.BoolFlag{ Name: "id", Usage: "Show list with post IDs (default)", }, cli.BoolFlag{ Name: "md", Usage: "Use with --url to return URLs with Markdown enabled", }, cli.BoolFlag{ Name: "url", Usage: "Show list with URLs", }, }, + }, { + Name: "blogs", + Usage: "List blogs", + Action: commands.CmdCollections, + Flags: []cli.Flag{ + cli.BoolFlag{ + Name: "url", + Usage: "Show list with URLs", + }, + }, + }, { + Name: "claim", + Usage: "Claim local unsynced posts", + Action: commands.CmdClaim, + Description: "This will claim any unsynced posts local to this machine. To see which posts these are run: writeas posts.", + Flags: []cli.Flag{ + cli.BoolFlag{ + Name: "verbose, v", + Usage: "Make the operation more talkative", + }, + }, + }, + { + Name: "auth", + Usage: "Authenticate with Write.as", + Action: commands.CmdAuth, + Flags: []cli.Flag{ + cli.BoolFlag{ + Name: "tor, t", + Usage: "Authenticate via Tor hidden service", + }, + cli.IntFlag{ + Name: "tor-port", + Usage: "Use a different port to connect to Tor", + Value: 9150, + }, + cli.BoolFlag{ + Name: "verbose, v", + Usage: "Make the operation more talkative", + }, + }, + }, + { + Name: "logout", + Usage: "Log out of Write.as", + Action: commands.CmdLogOut, + Flags: []cli.Flag{ + cli.BoolFlag{ + Name: "tor, t", + Usage: "Authenticate via Tor hidden service", + }, + cli.IntFlag{ + Name: "tor-port", + Usage: "Use a different port to connect to Tor", + Value: 9150, + }, + cli.BoolFlag{ + Name: "verbose, v", + Usage: "Make the operation more talkative", + }, + }, }, } cli.CommandHelpTemplate = `NAME: {{.Name}} - {{.Usage}} USAGE: writeas {{.Name}}{{if .Flags}} [command options]{{end}} [arguments...]{{if .Description}} DESCRIPTION: {{.Description}}{{end}}{{if .Flags}} OPTIONS: {{range .Flags}}{{.}} {{end}}{{ end }} ` - app.Run(os.Args) } -func initialize() { +func initialize(dataDirName string) { // Ensure we have a data directory to use - if !dataDirExists() { - createDataDir() - } -} - -func readStdIn() []byte { - numBytes, numChunks := int64(0), int64(0) - r := bufio.NewReader(os.Stdin) - fullPost := []byte{} - buf := make([]byte, 0, 1024) - for { - n, err := r.Read(buf[:cap(buf)]) - buf = buf[:n] - if n == 0 { - if err == nil { - continue - } - if err == io.EOF { - break + if !config.DataDirExists(dataDirName) { + err := config.CreateDataDir(dataDirName) + if err != nil { + if config.Debug() { + panic(err) + } else { + log.Errorln("Error creating data directory: %s", err) + return } - log.Fatal(err) } - numChunks++ - numBytes += int64(len(buf)) - - fullPost = append(fullPost, buf...) - if err != nil && err != io.EOF { - log.Fatal(err) - } - } - - return fullPost -} - -func handlePost(fullPost []byte, c *cli.Context) error { - tor := c.Bool("tor") || c.Bool("t") - if c.Int("tor-port") != 0 { - torPort = c.Int("tor-port") } - if tor { - Info(c, "Posting to hidden service...") - } else { - Info(c, "Posting...") - } - - return DoPost(c, fullPost, c.String("font"), false, tor, c.Bool("code")) } diff --git a/cmd/writeas/posts.go b/cmd/writeas/posts.go deleted file mode 100644 index 8150570..0000000 --- a/cmd/writeas/posts.go +++ /dev/null @@ -1,148 +0,0 @@ -package main - -import ( - "fmt" - "github.com/writeas/writeas-cli/fileutils" - "io/ioutil" - "os" - "path/filepath" - "strings" -) - -const ( - postsFile = "posts.psv" - separator = `|` -) - -// Post holds the basic authentication information for a Write.as post. -type Post struct { - ID string - EditToken string -} - -func userDataDir() string { - return filepath.Join(parentDataDir(), dataDirName) -} - -func dataDirExists() bool { - return fileutils.Exists(userDataDir()) -} - -func createDataDir() { - err := os.Mkdir(userDataDir(), 0700) - if err != nil { - if debug { - panic(err) - } else { - Errorln("Error creating data directory: %s", err) - return - } - } -} - -func addPost(id, token string) error { - f, err := os.OpenFile(filepath.Join(userDataDir(), postsFile), os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600) - if err != nil { - return fmt.Errorf("Error creating local posts list: %s", err) - } - defer f.Close() - - l := fmt.Sprintf("%s%s%s\n", id, separator, token) - - if _, err = f.WriteString(l); err != nil { - return fmt.Errorf("Error writing to local posts list: %s", err) - } - - return nil -} - -func tokenFromID(id string) string { - post := fileutils.FindLine(filepath.Join(userDataDir(), postsFile), id) - if post == "" { - return "" - } - - parts := strings.Split(post, separator) - if len(parts) < 2 { - return "" - } - - return parts[1] -} - -func removePost(id string) { - fileutils.RemoveLine(filepath.Join(userDataDir(), postsFile), id) -} - -func getPosts() *[]Post { - lines := fileutils.ReadData(filepath.Join(userDataDir(), postsFile)) - - posts := []Post{} - - if lines != nil && len(*lines) > 0 { - parts := make([]string, 2) - for _, l := range *lines { - parts = strings.Split(l, separator) - if len(parts) < 2 { - continue - } - posts = append(posts, Post{ID: parts[0], EditToken: parts[1]}) - } - } - - return &posts -} - -func composeNewPost() (string, *[]byte) { - f, err := fileutils.TempFile(os.TempDir(), "WApost", "txt") - if err != nil { - if debug { - panic(err) - } else { - Errorln("Error creating temp file: %s", err) - return "", nil - } - } - f.Close() - - cmd := editPostCmd(f.Name()) - if cmd == nil { - os.Remove(f.Name()) - - fmt.Println(noEditorErr) - return "", nil - } - cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr - if err := cmd.Start(); err != nil { - os.Remove(f.Name()) - - if debug { - panic(err) - } else { - Errorln("Error starting editor: %s", err) - return "", nil - } - } - - // If something fails past this point, the temporary post file won't be - // removed automatically. Calling function should handle this. - if err := cmd.Wait(); err != nil { - if debug { - panic(err) - } else { - Errorln("Editor finished with error: %s", err) - return "", nil - } - } - - post, err := ioutil.ReadFile(f.Name()) - if err != nil { - if debug { - panic(err) - } else { - Errorln("Error reading post: %s", err) - return "", nil - } - } - return f.Name(), &post -} diff --git a/commands/commands.go b/commands/commands.go new file mode 100644 index 0000000..0a4ba6a --- /dev/null +++ b/commands/commands.go @@ -0,0 +1,339 @@ +package commands + +import ( + "fmt" + "io/ioutil" + "os" + "text/tabwriter" + + "github.com/howeyc/gopass" + "github.com/writeas/writeas-cli/api" + "github.com/writeas/writeas-cli/config" + "github.com/writeas/writeas-cli/log" + cli "gopkg.in/urfave/cli.v1" +) + +func CmdPost(c *cli.Context) error { + _, err := api.HandlePost(api.ReadStdIn(), c) + return err +} + +func CmdNew(c *cli.Context) error { + fname, p := api.ComposeNewPost() + if p == nil { + // Assume composeNewPost already told us what the error was. Abort now. + os.Exit(1) + } + + // Ensure we have something to post + if len(*p) == 0 { + // Clean up temporary post + if fname != "" { + os.Remove(fname) + } + + log.InfolnQuit("Empty post. Bye!") + } + + _, err := api.HandlePost(*p, c) + if err != nil { + log.Errorln("Error posting: %s\n%s", err, config.MessageRetryCompose(fname)) + return cli.NewExitError("", 1) + } + + // Clean up temporary post + if fname != "" { + os.Remove(fname) + } + + return nil +} + +func CmdPublish(c *cli.Context) error { + filename := c.Args().Get(0) + if filename == "" { + return cli.NewExitError("usage: writeas publish ", 1) + } + content, err := ioutil.ReadFile(filename) + if err != nil { + return err + } + _, err = api.HandlePost(content, c) + + // TODO: write local file if directory is set + return err +} + +func CmdDelete(c *cli.Context) error { + friendlyID := c.Args().Get(0) + token := c.Args().Get(1) + if friendlyID == "" { + return cli.NewExitError("usage: writeas delete []", 1) + } + + u, _ := config.LoadUser(config.UserDataDir(c.App.ExtraInfo()["configDir"])) + if token == "" { + // Search for the token locally + token = api.TokenFromID(c, friendlyID) + if token == "" && u == nil { + log.Errorln("Couldn't find an edit token locally. Did you create this post here?") + log.ErrorlnQuit("If you have an edit token, use: writeas delete %s ", friendlyID) + } + } + + tor := config.IsTor(c) + if c.Int("tor-port") != 0 { + api.TorPort = c.Int("tor-port") + } + if tor { + log.Info(c, "Deleting via hidden service...") + } else { + log.Info(c, "Deleting...") + } + + err := api.DoDelete(c, friendlyID, token, tor) + if err != nil { + return cli.NewExitError(fmt.Sprintf("Couldn't delete remote copy: %v", err), 1) + } + + // TODO: Delete local file, if necessary + return nil +} + +func CmdUpdate(c *cli.Context) error { + friendlyID := c.Args().Get(0) + token := c.Args().Get(1) + if friendlyID == "" { + return cli.NewExitError("usage: writeas update []", 1) + } + + u, _ := config.LoadUser(config.UserDataDir(c.App.ExtraInfo()["configDir"])) + if token == "" { + // Search for the token locally + token = api.TokenFromID(c, friendlyID) + if token == "" && u == nil { + log.Errorln("Couldn't find an edit token locally. Did you create this post here?") + log.ErrorlnQuit("If you have an edit token, use: writeas update %s ", friendlyID) + } + } + + // Read post body + fullPost := api.ReadStdIn() + + tor := config.IsTor(c) + if c.Int("tor-port") != 0 { + api.TorPort = c.Int("tor-port") + } + if tor { + log.Info(c, "Updating via hidden service...") + } else { + log.Info(c, "Updating...") + } + + return api.DoUpdate(c, fullPost, friendlyID, token, c.String("font"), tor, c.Bool("code")) +} + +func CmdGet(c *cli.Context) error { + friendlyID := c.Args().Get(0) + if friendlyID == "" { + return cli.NewExitError("usage: writeas get ", 1) + } + + tor := config.IsTor(c) + if c.Int("tor-port") != 0 { + api.TorPort = c.Int("tor-port") + } + if tor { + log.Info(c, "Getting via hidden service...") + } else { + log.Info(c, "Getting...") + } + + return api.DoFetch(friendlyID, config.UserAgent(c), tor) +} + +func CmdAdd(c *cli.Context) error { + friendlyID := c.Args().Get(0) + token := c.Args().Get(1) + if friendlyID == "" || token == "" { + return cli.NewExitError("usage: writeas add ", 1) + } + + err := api.AddPost(c, friendlyID, token) + return err +} + +func CmdListPosts(c *cli.Context) error { + urls := c.Bool("url") + ids := c.Bool("id") + + var p api.Post + posts := api.GetPosts(c) + tw := tabwriter.NewWriter(os.Stdout, 10, 0, 2, ' ', tabwriter.TabIndent) + numPosts := len(*posts) + if ids || !urls && numPosts != 0 { + fmt.Fprintf(tw, "Local\t%s\t%s\t\n", "ID", "Token") + } else if numPosts != 0 { + fmt.Fprintf(tw, "Local\t%s\t%s\t\n", "URL", "Token") + } else { + fmt.Fprintf(tw, "No local posts found\n") + } + for i := range *posts { + p = (*posts)[numPosts-1-i] + if ids || !urls { + fmt.Fprintf(tw, "unsynced\t%s\t%s\t\n", p.ID, p.EditToken) + } else { + fmt.Fprintf(tw, "unsynced\t%s\t%s\t\n", getPostURL(c, p.ID), p.EditToken) + } + } + u, _ := config.LoadUser(config.UserDataDir(c.App.ExtraInfo()["configDir"])) + if u != nil { + remotePosts, err := api.GetUserPosts(c) + if err != nil { + fmt.Println(err) + } + + if len(remotePosts) > 0 { + identifier := "URL" + if ids || !urls { + identifier = "ID" + } + fmt.Fprintf(tw, "\nAccount\t%s\t%s\t\n", identifier, "Title") + } + for _, p := range remotePosts { + identifier := getPostURL(c, p.ID) + if ids || !urls { + identifier = p.ID + } + synced := "unsynced" + if p.Synced { + synced = "synced" + } + fmt.Fprintf(tw, "%s\t%s\t%s\t\n", synced, identifier, p.Title) + } + } + return tw.Flush() +} + +func getPostURL(c *cli.Context, slug string) string { + base := config.WriteasBaseURL + if config.IsDev() { + base = config.DevBaseURL + } + ext := "" + // Output URL in requested format + if c.Bool("md") { + ext = ".md" + } + return fmt.Sprintf("%s/%s%s", base, slug, ext) +} + +func CmdCollections(c *cli.Context) error { + u, err := config.LoadUser(config.UserDataDir(c.App.ExtraInfo()["configDir"])) + if err != nil { + return cli.NewExitError(fmt.Sprintf("couldn't load config: %v", err), 1) + } + if u == nil { + return cli.NewExitError("You must be authenticated to view collections.\nLog in first with: writeas auth ", 1) + } + colls, err := api.DoFetchCollections(c) + if err != nil { + return cli.NewExitError(fmt.Sprintf("Couldn't get collections for user %s: %v", u.User.Username, err), 1) + } + urls := c.Bool("url") + tw := tabwriter.NewWriter(os.Stdout, 8, 0, 2, ' ', tabwriter.TabIndent) + detail := "Title" + if urls { + detail = "URL" + } + fmt.Fprintf(tw, "%s\t%s\t\n", "Alias", detail) + for _, c := range colls { + dData := c.Title + if urls { + dData = c.URL + } + fmt.Fprintf(tw, "%s\t%s\t\n", c.Alias, dData) + } + tw.Flush() + return nil +} + +func CmdClaim(c *cli.Context) error { + u, err := config.LoadUser(config.UserDataDir(c.App.ExtraInfo()["configDir"])) + if err != nil { + return cli.NewExitError(fmt.Sprintf("couldn't load config: %v", err), 1) + } + if u == nil { + return cli.NewExitError("You must be authenticated to claim local posts.\nLog in first with: writeas auth ", 1) + } + + localPosts := api.GetPosts(c) + if len(*localPosts) == 0 { + return nil + } + + log.Info(c, "Claiming %d post(s) for %s...", len(*localPosts), u.User.Username) + results, err := api.ClaimPosts(c, localPosts) + if err != nil { + return cli.NewExitError(fmt.Sprintf("Failed to claim posts: %v", err), 1) + } + + var okCount, errCount int + for _, r := range *results { + id := r.ID + if id == "" { + // No top-level ID, so the claim was successful + id = r.Post.ID + } + status := fmt.Sprintf("Post %s...", id) + if r.ErrorMessage != "" { + log.Errorln("%serror: %v", status, r.ErrorMessage) + errCount++ + } else { + log.Info(c, "%sOK", status) + okCount++ + // only delete local if successful + api.RemovePost(c.App.ExtraInfo()["configDir"], id) + } + } + log.Info(c, "%d claimed, %d failed", okCount, errCount) + return nil +} + +func CmdAuth(c *cli.Context) error { + // Check configuration + u, err := config.LoadUser(config.UserDataDir(c.App.ExtraInfo()["configDir"])) + if err != nil { + return cli.NewExitError(fmt.Sprintf("couldn't load config: %v", err), 1) + } + if u != nil && u.AccessToken != "" { + return cli.NewExitError("You're already authenticated as "+u.User.Username+". Log out with: writeas logout", 1) + } + + // Validate arguments and get password + username := c.Args().Get(0) + if username == "" { + return cli.NewExitError("usage: writeas auth ", 1) + } + + fmt.Print("Password: ") + pass, err := gopass.GetPasswdMasked() + if err != nil { + return cli.NewExitError(fmt.Sprintf("error reading password: %v", err), 1) + } + + // Validate password + if len(pass) == 0 { + return cli.NewExitError("Please enter your password.", 1) + } + err = api.DoLogIn(c, username, string(pass)) + if err != nil { + return cli.NewExitError(fmt.Sprintf("error logging in: %v", err), 1) + } + + return nil +} + +func CmdLogOut(c *cli.Context) error { + return api.DoLogOut(c) +} diff --git a/config/build.go b/config/build.go new file mode 100644 index 0000000..1ca1c10 --- /dev/null +++ b/config/build.go @@ -0,0 +1,7 @@ +// +build !debug + +package config + +func Debug() bool { + return false +} diff --git a/config/build_debug.go b/config/build_debug.go new file mode 100644 index 0000000..b08138d --- /dev/null +++ b/config/build_debug.go @@ -0,0 +1,7 @@ +// +build debug + +package config + +func Debug() bool { + return true +} diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..4c9c59d --- /dev/null +++ b/config/config.go @@ -0,0 +1,63 @@ +package config + +import ( + "os" + "path/filepath" + + ini "gopkg.in/ini.v1" +) + +const ( + UserConfigFile = "config.ini" +) + +type ( + APIConfig struct { + } + + PostsConfig struct { + Directory string `ini:"directory"` + } + + UserConfig struct { + API APIConfig `ini:"api"` + Posts PostsConfig `ini:"posts"` + } +) + +func LoadConfig(dataDir string) (*UserConfig, error) { + // TODO: load config to var shared across app + cfg, err := ini.LooseLoad(filepath.Join(dataDir, UserConfigFile)) + if err != nil { + return nil, err + } + + // Parse INI file + uc := &UserConfig{} + err = cfg.MapTo(uc) + if err != nil { + return nil, err + } + return uc, nil +} + +func SaveConfig(dataDir string, uc *UserConfig) error { + cfg := ini.Empty() + err := ini.ReflectFrom(cfg, uc) + if err != nil { + return err + } + + return cfg.SaveTo(filepath.Join(dataDir, UserConfigFile)) +} + +var editors = []string{"WRITEAS_EDITOR", "EDITOR"} + +func GetConfiguredEditor() string { + for _, v := range editors { + if e := os.Getenv(v); e != "" { + return e + } + } + return "" +} diff --git a/config/dev.go b/config/dev.go new file mode 100644 index 0000000..41dbf5a --- /dev/null +++ b/config/dev.go @@ -0,0 +1,9 @@ +package config + +import ( + "os" +) + +func IsDev() bool { + return os.Getenv("WRITEAS_DEV") == "1" +} diff --git a/config/directories.go b/config/directories.go new file mode 100644 index 0000000..8373835 --- /dev/null +++ b/config/directories.go @@ -0,0 +1,20 @@ +package config + +import ( + "os" + "path/filepath" + + "github.com/writeas/writeas-cli/fileutils" +) + +func UserDataDir(dataDirName string) string { + return filepath.Join(parentDataDir(), dataDirName) +} + +func DataDirExists(dataDirName string) bool { + return fileutils.Exists(UserDataDir(dataDirName)) +} + +func CreateDataDir(dataDirName string) error { + return os.Mkdir(UserDataDir(dataDirName), 0700) +} diff --git a/cmd/writeas/posts_nix.go b/config/files_nix.go similarity index 66% rename from cmd/writeas/posts_nix.go rename to config/files_nix.go index ee4d78b..0c10f04 100644 --- a/cmd/writeas/posts_nix.go +++ b/config/files_nix.go @@ -1,43 +1,43 @@ // +build !windows -package main +package config import ( "fmt" - "github.com/mitchellh/go-homedir" "os/exec" + + homedir "github.com/mitchellh/go-homedir" ) const ( - dataDirName = ".writeas" - noEditorErr = "Couldn't find default editor. Try setting $EDITOR environment variable in ~/.profile" + NoEditorErr = "Couldn't find default editor. Try setting $EDITOR environment variable in ~/.profile" ) func parentDataDir() string { dir, err := homedir.Dir() if err != nil { panic(err) } return dir } -func editPostCmd(fname string) *exec.Cmd { - editor := getConfiguredEditor() +func EditPostCmd(fname string) *exec.Cmd { + editor := GetConfiguredEditor() if editor == "" { // Fall back to default editor path, err := exec.LookPath("vim") if err != nil { path, err = exec.LookPath("nano") if err != nil { return nil } } editor = path } return exec.Command(editor, fname) } -func messageRetryCompose(fname string) string { +func MessageRetryCompose(fname string) string { return fmt.Sprintf("To retry this post, run:\n cat %s | writeas", fname) } diff --git a/cmd/writeas/posts_win.go b/config/files_win.go similarity index 65% rename from cmd/writeas/posts_win.go rename to config/files_win.go index c8b080a..026b803 100644 --- a/cmd/writeas/posts_win.go +++ b/config/files_win.go @@ -1,27 +1,26 @@ // +build windows -package main +package config import ( "fmt" "os" "os/exec" ) const ( - dataDirName = "Write.as" - noEditorErr = "Error getting default editor. You shouldn't see this, so let us know you did: hello@write.as" + NoEditorErr = "Error getting default editor. You shouldn't see this, so let us know you did: hello@write.as" ) func parentDataDir() string { return os.Getenv("APPDATA") } -func editPostCmd(fname string) *exec.Cmd { +func EditPostCmd(fname string) *exec.Cmd { // NOTE this won't work if fname contains spaces. return exec.Command("cmd", "/C copy con "+fname) } -func messageRetryCompose(fname string) string { +func MessageRetryCompose(fname string) string { return fmt.Sprintf("To retry this post, run:\n type %s | writeas.exe", fname) } diff --git a/config/flags.go b/config/flags.go new file mode 100644 index 0000000..2c17e23 --- /dev/null +++ b/config/flags.go @@ -0,0 +1,50 @@ +package config + +import ( + "gopkg.in/urfave/cli.v1" +) + +// Available flags for creating posts +var PostFlags = []cli.Flag{ + cli.StringFlag{ + Name: "c, b", + Usage: "Optional blog to post to", + Value: "", + }, + cli.BoolFlag{ + Name: "tor, t", + Usage: "Perform action on Tor hidden service", + }, + cli.IntFlag{ + Name: "tor-port", + Usage: "Use a different port to connect to Tor", + Value: 9150, + }, + cli.BoolFlag{ + Name: "code", + Usage: "Specifies this post is code", + }, + cli.BoolFlag{ + Name: "md", + Usage: "Returns post URL with Markdown enabled", + }, + cli.BoolFlag{ + Name: "verbose, v", + Usage: "Make the operation more talkative", + }, + cli.StringFlag{ + Name: "font", + Usage: "Sets post font to given value", + Value: DefaultFont, + }, + cli.StringFlag{ + Name: "lang", + Usage: "Sets post language to given ISO 639-1 language code", + Value: "", + }, + cli.StringFlag{ + Name: "user-agent", + Usage: "Sets the User-Agent for API requests", + Value: "", + }, +} diff --git a/cmd/writeas/fonts.go b/config/fonts.go similarity index 81% rename from cmd/writeas/fonts.go rename to config/fonts.go index 28684e9..22fc56b 100644 --- a/cmd/writeas/fonts.go +++ b/config/fonts.go @@ -1,46 +1,46 @@ -package main +package config import ( "fmt" ) // postFont represents a valid post appearance value in the API. type postFont string // Valid appearance types for posts. const ( PostFontNormal postFont = "norm" PostFontSans = "sans" PostFontMono = "mono" PostFontWrap = "wrap" PostFontCode = "code" ) var postFontMap = map[string]postFont{ "norm": PostFontNormal, "normal": PostFontNormal, "serif": PostFontNormal, "sans": PostFontSans, "sansserif": PostFontSans, "mono": PostFontMono, "monospace": PostFontMono, "wrap": PostFontWrap, "code": PostFontCode, } -func getFont(code bool, font string) string { +func GetFont(code bool, font string) string { if code { - if font != "" && font != defaultFont { + if font != "" && font != DefaultFont { fmt.Printf("A non-default font '%s' and --code flag given. 'code' type takes precedence.\n", font) } return "code" } // Validate font value if f, ok := postFontMap[font]; ok { return string(f) } - fmt.Printf("Font '%s' invalid. Using default '%s'\n", font, defaultFont) - return string(defaultFont) + fmt.Printf("Font '%s' invalid. Using default '%s'\n", font, DefaultFont) + return string(DefaultFont) } diff --git a/config/options.go b/config/options.go new file mode 100644 index 0000000..1abf9ee --- /dev/null +++ b/config/options.go @@ -0,0 +1,56 @@ +package config + +import ( + "github.com/cloudfoundry/jibber_jabber" + "github.com/writeas/writeas-cli/log" + cli "gopkg.in/urfave/cli.v1" +) + +// Application constants. +const ( + Version = "2.0" + defaultUserAgent = "writeas-cli v" + Version + // Defaults for posts on Write.as. + DefaultFont = PostFontMono + WriteasBaseURL = "https://write.as" + DevBaseURL = "https://development.write.as" + TorBaseURL = "http://writeas7pm7rcdqg.onion" +) + +func UserAgent(c *cli.Context) string { + ua := c.String("user-agent") + if ua == "" { + return defaultUserAgent + } + return ua + " (" + defaultUserAgent + ")" +} + +func IsTor(c *cli.Context) bool { + return c.Bool("tor") || c.Bool("t") +} + +func Language(c *cli.Context, auto bool) string { + if l := c.String("lang"); l != "" { + return l + } + if !auto { + return "" + } + // Automatically detect language + l, err := jibber_jabber.DetectLanguage() + if err != nil { + log.Info(c, "Language detection failed: %s", err) + return "" + } + return l +} + +func Collection(c *cli.Context) string { + if coll := c.String("c"); coll != "" { + return coll + } + if coll := c.String("b"); coll != "" { + return coll + } + return "" +} diff --git a/config/user.go b/config/user.go new file mode 100644 index 0000000..21dd8f9 --- /dev/null +++ b/config/user.go @@ -0,0 +1,47 @@ +package config + +import ( + "encoding/json" + "io/ioutil" + "path/filepath" + + writeas "github.com/writeas/go-writeas/v2" + "github.com/writeas/writeas-cli/fileutils" +) + +const UserFile = "user.json" + +func LoadUser(dataDir string) (*writeas.AuthUser, error) { + fname := filepath.Join(dataDir, UserFile) + userJSON, err := ioutil.ReadFile(fname) + if err != nil { + if !fileutils.Exists(fname) { + // Don't return a file-not-found error + return nil, nil + } + return nil, err + } + + // Parse JSON file + u := &writeas.AuthUser{} + err = json.Unmarshal(userJSON, u) + if err != nil { + return nil, err + } + return u, nil +} + +func SaveUser(dataDir string, u *writeas.AuthUser) error { + // Marshal struct into pretty-printed JSON + userJSON, err := json.MarshalIndent(u, "", " ") + if err != nil { + return err + } + + // Save file + err = ioutil.WriteFile(filepath.Join(dataDir, UserFile), userJSON, 0600) + if err != nil { + return err + } + return nil +} diff --git a/fileutils/fileutils.go b/fileutils/fileutils.go index ba36356..7e4c354 100644 --- a/fileutils/fileutils.go +++ b/fileutils/fileutils.go @@ -1,107 +1,111 @@ package fileutils import ( "bufio" "fmt" "os" "strings" ) // Exists returns whether or not the given file exists func Exists(p string) bool { - if _, err := os.Stat(p); err == nil { + if _, err := os.Stat(p); !os.IsNotExist(err) { return true } return false } // WriteData writes data to the given path, creating the file if necessary. func WriteData(path string, data []byte) { f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600) if err != nil { fmt.Println(err) } // TODO: check for Close() errors // https://github.com/ncw/swift/blob/master/swift.go#L170 defer f.Close() _, err = f.Write(data) if err != nil { fmt.Println(err) } } // ReadData returns file data as an array of lines from the file. func ReadData(p string) *[]string { f, err := os.Open(p) if err != nil { return nil } defer f.Close() lines := []string{} scanner := bufio.NewScanner(f) for scanner.Scan() { lines = append(lines, scanner.Text()) } if err := scanner.Err(); err != nil { return nil } return &lines } // RemoveLine searches for the line that starts with the given value and, // if found, removes it and saves the updated file. func RemoveLine(p, startsWith string) { f, err := os.Open(p) if err != nil { return } defer f.Close() var outText string found := false scanner := bufio.NewScanner(f) for scanner.Scan() { if strings.HasPrefix(scanner.Text(), startsWith) { found = true } else { outText += scanner.Text() + string('\n') } } if err := scanner.Err(); err != nil { return } if found { WriteData(p, []byte(outText)) } } // FindLine searches the given file for a line that begins with the given // string. func FindLine(p, startsWith string) string { f, err := os.Open(p) if err != nil { return "" } defer f.Close() scanner := bufio.NewScanner(f) for scanner.Scan() { if strings.HasPrefix(scanner.Text(), startsWith) { return scanner.Text() } } if err := scanner.Err(); err != nil { return "" } return "" } + +func DeleteFile(p string) error { + return os.Remove(p) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..346f6ef --- /dev/null +++ b/go.mod @@ -0,0 +1,25 @@ +module github.com/writeas/writeas-cli + +require ( + code.as/core/socks v1.0.0 + github.com/atotto/clipboard v0.1.1 + github.com/cloudfoundry/jibber_jabber v0.0.0-20151120183258-bcc4c8345a21 + github.com/gopherjs/gopherjs v0.0.0-20181103185306-d547d1d9531e // indirect + github.com/howeyc/gopass v0.0.0-20170109162249-bf9dde6d0d2c + github.com/jtolds/gls v4.2.1+incompatible // indirect + github.com/microcosm-cc/bluemonday v1.0.1 // indirect + github.com/mitchellh/go-homedir v1.0.0 + github.com/onsi/ginkgo v1.8.0 // indirect + github.com/onsi/gomega v1.5.0 // indirect + github.com/shurcooL/sanitized_anchor_name v0.0.0-20170918181015-86672fcb3f95 // indirect + github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d // indirect + github.com/smartystreets/goconvey v0.0.0-20181108003508-044398e4856c // indirect + github.com/writeas/go-writeas/v2 v2.0.0 + github.com/writeas/saturday v0.0.0-20170402010311-f455b05c043f // indirect + github.com/writeas/web-core v0.0.0-20181111165528-05f387ffa1b3 + golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9 // indirect + golang.org/x/net v0.0.0-20181217023233-e147a9138326 // indirect + golang.org/x/sys v0.0.0-20181213200352-4d1cda033e06 // indirect + gopkg.in/ini.v1 v1.39.3 + gopkg.in/urfave/cli.v1 v1.20.0 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..d135529 --- /dev/null +++ b/go.sum @@ -0,0 +1,69 @@ +code.as/core/socks v0.0.0-20180906144846-5be269b4e664 h1:zWSFbwkYSuZ2PjvHqYDE/dhd9CCcsbSvUIRx8hIed3I= +code.as/core/socks v0.0.0-20180906144846-5be269b4e664/go.mod h1:BAXBy5O9s2gmw6UxLqNJcVbWY7C/UPs+801CcSsfWOY= +code.as/core/socks v1.0.0 h1:SPQXNp4SbEwjOAP9VzUahLHak8SDqy5n+9cm9tpjZOs= +code.as/core/socks v1.0.0/go.mod h1:BAXBy5O9s2gmw6UxLqNJcVbWY7C/UPs+801CcSsfWOY= +github.com/atotto/clipboard v0.1.1 h1:WSoEbAS70E5gw8FbiqFlp69MGsB6dUb4l+0AGGLiVGw= +github.com/atotto/clipboard v0.1.1/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= +github.com/cloudfoundry/jibber_jabber v0.0.0-20151120183258-bcc4c8345a21 h1:tuijfIjZyjZaHq9xDUh0tNitwXshJpbLkqMOJv4H3do= +github.com/cloudfoundry/jibber_jabber v0.0.0-20151120183258-bcc4c8345a21/go.mod h1:po7NpZ/QiTKzBKyrsEAxwnTamCoh8uDk/egRpQ7siIc= +github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/gopherjs/gopherjs v0.0.0-20181103185306-d547d1d9531e h1:JKmoR8x90Iww1ks85zJ1lfDGgIiMDuIptTOhJq+zKyg= +github.com/gopherjs/gopherjs v0.0.0-20181103185306-d547d1d9531e/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/howeyc/gopass v0.0.0-20170109162249-bf9dde6d0d2c h1:kQWxfPIHVLbgLzphqk3QUflDy9QdksZR4ygR807bpy0= +github.com/howeyc/gopass v0.0.0-20170109162249-bf9dde6d0d2c/go.mod h1:lADxMC39cJJqL93Duh1xhAs4I2Zs8mKS89XWXFGp9cs= +github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/jtolds/gls v4.2.1+incompatible h1:fSuqC+Gmlu6l/ZYAoZzx2pyucC8Xza35fpRVWLVmUEE= +github.com/jtolds/gls v4.2.1+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= +github.com/microcosm-cc/bluemonday v1.0.1 h1:SIYunPjnlXcW+gVfvm0IlSeR5U3WZUOLfVmqg85Go44= +github.com/microcosm-cc/bluemonday v1.0.1/go.mod h1:hsXNsILzKxV+sX77C5b8FSuKF00vh2OMYv+xgHpAMF4= +github.com/mitchellh/go-homedir v1.0.0 h1:vKb8ShqSby24Yrqr/yDYkuFz8d0WUjys40rvnGC8aR0= +github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.8.0 h1:VkHVNpR4iVnU8XQR6DBm8BqYjN7CRzw+xKUbVVbbW9w= +github.com/onsi/ginkgo v1.8.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/gomega v1.5.0 h1:izbySO9zDPmjJ8rDjLvkA2zJHIo+HkYXHnf7eN7SSyo= +github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/shurcooL/sanitized_anchor_name v0.0.0-20170918181015-86672fcb3f95 h1:/vdW8Cb7EXrkqWGufVMES1OH2sU9gKVb2n9/1y5NMBY= +github.com/shurcooL/sanitized_anchor_name v0.0.0-20170918181015-86672fcb3f95/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v0.0.0-20181108003508-044398e4856c h1:Ho+uVpkel/udgjbwB5Lktg9BtvJSh2DT0Hi6LPSyI2w= +github.com/smartystreets/goconvey v0.0.0-20181108003508-044398e4856c/go.mod h1:XDJAKZRPZ1CvBcN2aX5YOUTYGHki24fSF0Iv48Ibg0s= +github.com/writeas/go-writeas/v2 v2.0.0 h1:KjDI5bQSAIH0IzkKW3uGoY98I1A4DrBsSqBklgyOvHw= +github.com/writeas/go-writeas/v2 v2.0.0/go.mod h1:9sjczQJKmru925fLzg0usrU1R1tE4vBmQtGnItUMR0M= +github.com/writeas/impart v0.0.0-20180808220913-fef51864677b h1:vsZIsYneuNwXMsnh0lKviEVc8WeIqBG4RTmGWU86HpI= +github.com/writeas/impart v0.0.0-20180808220913-fef51864677b/go.mod h1:sUkQZZHJfrVNsoD4QbkrYrRSQtCN3SaUPWKdohmFKT8= +github.com/writeas/impart v1.1.0 h1:nPnoO211VscNkp/gnzir5UwCDEvdHThL5uELU60NFSE= +github.com/writeas/impart v1.1.0/go.mod h1:g0MpxdnTOHHrl+Ca/2oMXUHJ0PcRAEWtkCzYCJUXC9Y= +github.com/writeas/saturday v0.0.0-20170402010311-f455b05c043f h1:yyFguE0EopK8e7I7/AB1JWM925OFOI1uFhTM/SwXAnQ= +github.com/writeas/saturday v0.0.0-20170402010311-f455b05c043f/go.mod h1:ETE1EK6ogxptJpAgUbcJD0prAtX48bSloie80+tvnzQ= +github.com/writeas/web-core v0.0.0-20181111165528-05f387ffa1b3 h1:mKD4DMZuiZWrn1k/f+1wLmBu9SYMrydy9om+eeo9kjA= +github.com/writeas/web-core v0.0.0-20181111165528-05f387ffa1b3/go.mod h1:Si3chV7VWgY8CsV+3gRolMXSO2Vx1ZFAQ/mkrpvmyEE= +golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9 h1:mKdxBk7AujPs8kU4m80U72y/zjbZ3UcXC7dClwKbUI0= +golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181217023233-e147a9138326 h1:iCzOf0xz39Tstp+Tu/WwyGjUXCk34QhQORRxBeXXTA4= +golang.org/x/net v0.0.0-20181217023233-e147a9138326/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181213200352-4d1cda033e06 h1:0oC8rFnE+74kEmuHZ46F6KHsMr5Gx2gUQPuNz28iQZM= +golang.org/x/sys v0.0.0-20181213200352-4d1cda033e06/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/ini.v1 v1.39.3 h1:+LGDwGPQXrK1zLmDY5GMdgX7uNvs4iS+9fIRAGaDBbg= +gopkg.in/ini.v1 v1.39.3/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/urfave/cli.v1 v1.20.0 h1:NdAVW6RYxDif9DhDHaAortIu956m2c0v+09AZBPTbE0= +gopkg.in/urfave/cli.v1 v1.20.0/go.mod h1:vuBzUtMdQeixQj8LVd+/98pzhxNGQoyuPBlsXHOQNO0= +gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/cmd/writeas/errors.go b/log/errors.go similarity index 66% rename from cmd/writeas/errors.go rename to log/errors.go index 9acc555..8ce959f 100644 --- a/cmd/writeas/errors.go +++ b/log/errors.go @@ -1,9 +1,10 @@ -package main +package log import ( "errors" ) +// TODO: this is never used? var ( ErrPostNotFound = errors.New("Post not found.") ) diff --git a/cmd/writeas/logging.go b/log/logging.go similarity index 89% rename from cmd/writeas/logging.go rename to log/logging.go index 98fb5ec..a514a7c 100644 --- a/cmd/writeas/logging.go +++ b/log/logging.go @@ -1,32 +1,33 @@ -package main +package log import ( "fmt" - "gopkg.in/urfave/cli.v1" "os" + + cli "gopkg.in/urfave/cli.v1" ) // Info logs general diagnostic messages, shown only when the -v or --verbose // flag is provided. func Info(c *cli.Context, s string, p ...interface{}) { if c.Bool("v") || c.Bool("verbose") { fmt.Fprintf(os.Stderr, s+"\n", p...) } } // InfolnQuit logs the message to stderr and exits normally (without an error). func InfolnQuit(s string, p ...interface{}) { fmt.Fprintf(os.Stderr, s+"\n", p...) os.Exit(0) } -// Error +// Errorln logs the message to stderr func Errorln(s string, p ...interface{}) { fmt.Fprintf(os.Stderr, s+"\n", p...) } // ErrorlnQuit logs the message to stderr and exits with an error code. func ErrorlnQuit(s string, p ...interface{}) { fmt.Fprintf(os.Stderr, s+"\n", p...) os.Exit(1) }