├── .gitignore
├── ChangeLog.org
├── LICENSE
├── README.org
├── Rakefile
├── images
└── screenshot1.png
├── org-id-cleanup.el
├── rake_config.yml
└── test
├── .nosearch
└── oidclpt.el
/.gitignore:
--------------------------------------------------------------------------------
1 | *.elc
2 | *.new
3 | \#*#
4 | .#*
5 | *~
6 | elpa
7 | org-id-locations-for-test
8 | oidclpt-ert-work.org
9 | backup
10 |
--------------------------------------------------------------------------------
/ChangeLog.org:
--------------------------------------------------------------------------------
1 | * 1.7 until 2023-03-10 Fr
2 |
3 | - Compute differences to previous invocation and offer files to be
4 | added back
5 | - Show headings along with IDs for deletion
6 |
7 | * 1.6 until 2021-05-24 Mo
8 |
9 | - Restructured instructions
10 | - Various clarifications
11 |
12 | * 1.5 until 2021-03-20 Sa
13 |
14 | - Scan more files for IDs
15 | - Write list of files to log
16 | - Offer to revert all changes
17 | - More hints
18 |
19 | * 1.4 until 2020-09-14 Mo
20 |
21 | - Clarification regarding archives
22 | - Rely on org-id-files
23 | - Refactoring
24 |
25 | * 1.3 until 2020-05-23 Sa
26 |
27 | - Write a log of deleted IDs
28 |
29 | * 1.2 until 2020-05-03 Su
30 |
31 | - Adding tests
32 | - Preparing for melpa
33 |
34 | * 1.1 until 2020-05-01 Fr
35 |
36 | - Respecting attachments
37 | - Refactoring
38 |
39 | * 1.0 until 2020-04-13 Mo
40 |
41 | - Initial Version
42 |
43 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
341 |
--------------------------------------------------------------------------------
/README.org:
--------------------------------------------------------------------------------
1 | * org-id-cleanup
2 |
3 | Interactively cleanup unreferenced IDs of org-id.
4 |
5 | org-id-cleanup is a package for org-mode within emacs.
6 |
7 | Read below for a description.
8 |
9 | The current version is 1.7.1.
10 |
11 | ** Table of Contents
12 |
13 | - [[#screenshot][Screenshot]]
14 | - [[#about-this-package][About this Package]]
15 | - [[#files][Files]]
16 | - [[#releasing-a-new-version][Releasing a new version]]
17 | - [[#latest-change-log][Latest Change Log]]
18 |
19 | ** Screenshot
20 |
21 | The screenshot shows step 2 of the assistant after pushing the go-button.
22 |
23 | [[images/screenshot1.png]]
24 | ** About this Package
25 |
26 | *** Purpose
27 |
28 | Interactively find and clean up unused IDs of org-id.
29 | The term 'unused' refers to IDs, that have been created by org-id
30 | regularly, but are now no longer referenced from anywhere within in org.
31 | This might e.g. happen by deleting a link, that once referenced such an id.
32 |
33 | Normal usage of org-id does not lead to a lot of such unused IDs, and
34 | org-id does not suffer much from them.
35 |
36 | However, some usage patterns or packages (like org-working-set) may
37 | produce a larger number of such unused IDs; in such cases it might be
38 | helpful to clean up with org-id-cleanup.
39 |
40 | *** Setup
41 |
42 | org-id-cleanup should be installed with package.el or use-package
43 |
44 | ** Files
45 |
46 | *** Implementation
47 |
48 | - org-id-cleanup.el :: The complete lisp source
49 |
50 | *** Building
51 |
52 | - Rakefile :: Helpful Ruby-Tasks for building
53 |
54 | *** Tests
55 |
56 | In subdir tests.
57 |
58 | - oidclpt.el :: ert-tests for org-id-cleanup
59 | - run-tests.ps1 :: Windows command file to start an emacs, which
60 | is specifically prepared for the tests
61 | - run-tests.el :: Customizations for the tests
62 |
63 | ** Releasing a new version
64 |
65 | *** Testing and checking
66 |
67 | - rake test
68 | - (byte-compile-file "org-id-cleanup.el")
69 | - elint-current-buffer
70 | - checkdoc
71 | - package-lint-current-buffer ;; ignore messages about org-ws--prefix
72 |
73 | *** Preparing
74 |
75 | - Update Version number in org-id-cleanup.el
76 | - Update Change Log in org-id-cleanup.el
77 | - Check and update Commentary in org-id-cleanup.el
78 | - Run rake to copy those pieces of information into
79 | README.org and ChangeLog.org
80 | - git add/commit as appropriate
81 | - v=x.y.z ; git tag -a -m $v $v ; git push ; git push --tags
82 |
83 | ** Latest Change Log
84 |
85 | See ChangeLog.org for older entries.
86 |
87 | *** 1.7
88 |
89 | - Compute differences to previous invocation and offer files to be
90 | added back
91 | - Show headings along with IDs for deletion
92 |
93 | *** 1.6
94 |
95 | - Restructured instructions
96 | - Various clarifications
97 |
98 | *** 1.5
99 |
100 | - Scan more files for IDs
101 | - Write list of files to log
102 | - Offer to revert all changes
103 | - More hints
104 |
105 | *** 1.4
106 |
107 | - Clarification regarding archives
108 | - Rely on org-id-files
109 | - Refactoring
110 |
111 | *** 1.3
112 |
113 | - Write a log of deleted IDs
114 |
115 | *** 1.2
116 |
117 | - Adding tests
118 | - Preparing for melpa
119 |
120 | *** 1.1
121 |
122 | - Respecting attachments
123 | - Refactoring
124 |
125 | *** 1.0
126 |
127 | - Initial Version
128 |
129 |
--------------------------------------------------------------------------------
/Rakefile:
--------------------------------------------------------------------------------
1 | #!/usr/bin/ruby
2 |
3 | #
4 | # Common Rakefile for multiple elisp-projects; updates itself (if dir exists) from
5 | #
6 | # ../rakefile-for-elisp/Rakefile
7 | #
8 | # and vice versa.
9 | #
10 | # Configure via rake_config.yml
11 | #
12 |
13 | require 'fileutils'
14 | include FileUtils
15 | require 'yaml'
16 | require 'set'
17 | require 'open3'
18 |
19 | #
20 | # Global variables
21 | #
22 | # Configuration and options
23 | $conf = YAML::load(File.open('rake_config.yml'))
24 | $conf.transform_keys!(&:to_sym)
25 | $conf[:file] = 'rake_config.yml'
26 | $v = (verbose == true)
27 |
28 | # Shared information between tasks
29 | # from lisp-source
30 | $version_lisp = nil
31 | $commentary_lisp = Hash.new
32 | $changelog_lisp = Hash.new
33 | # from changelog
34 | $changelog = Hash.new
35 | $changelog_until = Hash.new
36 |
37 | #
38 | # Helper functions
39 | #
40 | def heading text, large = false, warn = false
41 | if large
42 | puts "\n"
43 | print "\e[32m"
44 | dash = "==="
45 | puts dash * 12
46 | puts "#{dash} #{text}"
47 | puts dash * 12
48 | else
49 | print "\e[#{warn ? 35 : 33}m"
50 | puts "--- #{text}"
51 | end
52 | print "\e[0m"
53 | end
54 |
55 |
56 | def compare_semver one,two
57 | vs = [one, two].map do |x|
58 | x.match(/(\d+)\.(\d+)/) || abort("Argument '#{x}' does not contain a semantic version number")
59 | end
60 | ( 2*(vs[0][1].to_i<=>vs[1][1].to_i) + (vs[0][2].to_i<=>vs[1][2].to_i) ) <=> 0
61 | end
62 |
63 |
64 | def accept fname,nname
65 | heading "Accept changes to #{fname} ?"
66 | system "diff #{fname} #{nname}"
67 | if $? == 0
68 | puts "No differences between #{fname} and #{nname}."
69 | rm nname
70 | else
71 | puts "\n\n"
72 | system "ls -l #{fname} #{nname}"
73 | heading "Changes to #{fname}.\nPlease review 'diff old new' and output of 'ls'\nType RETURN to accept or Ctrl-c Ctrl-c to reject:"
74 | $stdin.gets
75 | make_backup fname
76 | mv nname,fname
77 | end
78 | end
79 |
80 |
81 | def make_backup file
82 | dir = File.dirname(file) + '/backup'
83 | mkdir dir,{:verbose => $v} unless File.directory?(dir)
84 | backs = [ file ] + (1..12).map {|i| dir + '/' + File.basename(file) + "_" + i.to_s}
85 | pairs = backs[0..-2].zip(backs[1..-1]).reverse
86 | pairs.each do |p|
87 | next unless File.exist?(p[0])
88 | cp p[0],p[1],{:verbose => $v}
89 | end
90 | end
91 |
92 |
93 | def maybe_copy from,to
94 | puts "Maybe copy #{from} to #{to}" if $v
95 | [from, to].each {|f| return false unless File.exist?(f)}
96 | return false if File.mtime(to) > File.mtime(from)
97 | system("diff -q #{from} #{to} >/dev/null 2>&1")
98 | return false if $?.exitstatus == 0
99 | make_backup to
100 | cp from,to,{:verbose => $v}
101 | return true
102 | end
103 |
104 |
105 | def brushup text
106 | text.sub!(/\A[\s\n]+/,'')
107 | text.sub!(/[\s\n]+\Z/,'')
108 | text.chomp!
109 | end
110 |
111 |
112 | def write_as_org file, level, hash, &compare
113 | keys = hash.keys
114 | keys = keys.sort(&compare) if compare
115 | keys.each do |key|
116 | file.puts '*' * level + " #{key}\n\n"
117 | hash[key].lines.each {|l| file.puts (' ' * (level+1) + l).rstrip}
118 | file.puts "\n"
119 | end
120 | pp hash if $v
121 | end
122 |
123 |
124 | def forward_to file, text
125 | line = nil
126 | begin
127 | line = file.gets
128 | end until !line || line.start_with?(text)
129 | line
130 | end
131 |
132 | #
133 | # Individual tasks
134 | #
135 | #
136 | # Tasks, that collect information, no desc to avoid them beeing listed with -T
137 | #
138 |
139 | # Compare with rakefile in other dir and update
140 | task :update_rake do
141 | this_rf = __FILE__
142 | parent_rf = File.expand_path('..', File.dirname(this_rf)) + '/rakefile-for-elisp/Rakefile'
143 | system("touch -t 190001010000 #{parent_rf} >/dev/null 2>&1") unless File.exist?(parent_rf)
144 |
145 | if maybe_copy this_rf, parent_rf
146 | heading "Updated #{parent_rf} from #{this_rf}"
147 | elsif maybe_copy parent_rf, this_rf
148 | heading "This rakefile #{this_rf} has been updated from #{parent_rf}; please rerun"
149 | exit
150 | end
151 | end
152 |
153 |
154 |
155 | # Extract version from sourcefile
156 | task :extract_version => [:update_rake] do
157 |
158 | heading "Extract version from #{$conf[:source]}"
159 |
160 | File.open($conf[:source]).each do |line|
161 | if line.match(/^;; Version: (\d+\.\d+\.\d+)\s*/)
162 | $version_lisp = Regexp.last_match[1]
163 | puts $version_lisp
164 | break
165 | end
166 | end
167 | end
168 |
169 |
170 | # Extract commentary from sourcefile
171 | task :extract_commentary => [:update_rake] do
172 |
173 | heading "Extract commentary from #{$conf[:source]}"
174 |
175 | commentary_keys_matcher = Regexp.new('^;; (' + $conf[:required_pieces_commentary].join('|') + '):\s*$')
176 | key = nil
177 |
178 | File.open($conf[:source]).
179 | drop_while { |line| !line.start_with?(';;; Commentary:') }.
180 | drop(2).take_while { |line| line.start_with?(';;') }.each do |line|
181 | if line.match(commentary_keys_matcher)
182 | key = Regexp.last_match[1]
183 | $commentary_lisp[key] = ''
184 | puts key
185 | else
186 | $commentary_lisp[key] += line.sub(/^;;( )?/,'').rstrip + "\n" if key
187 | end
188 | end
189 |
190 | $commentary_lisp.each_key do |key|
191 | brushup $commentary_lisp[key]
192 | end
193 | pp $commentary_lisp if $v
194 |
195 | pieces_seen = Set.new($commentary_lisp.keys)
196 | pieces_required = Set.new($conf[:required_pieces_commentary])
197 | abort "ERROR: Pieces of commentary seen #{pieces_seen} does not equal pieces of commentary required #{pieces_required}" unless pieces_seen == pieces_required
198 | end
199 |
200 |
201 | # Extract change log from sourcefile
202 | task :extract_changelog_lisp => [:extract_version] do
203 |
204 | heading "Extract Changelog from #{$conf[:source]}"
205 | version = offset = nil
206 |
207 | File.open($conf[:source]).each.
208 | drop_while { |line| !line.start_with?(';;; Change Log:') }.
209 | drop(2).
210 | take_while { |line| line.start_with?(';;') }.each do |line|
211 | if line.match(/^(;;\s+)Version (\d+\.\d+)\s*/)
212 | version = Regexp.last_match[2]
213 | $changelog_lisp[version] = ''
214 | offset = Regexp.last_match[1]
215 | puts version
216 | elsif version
217 | $changelog_lisp[version] += (line[offset.length..-1] || '').rstrip + "\n"
218 | end
219 | end
220 |
221 | $changelog_lisp.each_key do |version|
222 | brushup $changelog_lisp[version]
223 | end
224 |
225 | pp $changelog_lisp if $v
226 |
227 | version_lisp_latest = $changelog_lisp.keys.max {|a,b| compare_semver(a,b)}
228 | abort "Mismatch in #{$conf[:source]}: Latest version from Changelog '#{version_lisp_latest}' does not match version specified in header '#{$version_lisp}'" unless $version_lisp.sub(/\.\d+$/,'') == version_lisp_latest
229 |
230 | end
231 |
232 |
233 | # Extract change log from changelog
234 | task :extract_changelog => [:extract_changelog_lisp] do
235 |
236 | fname = 'ChangeLog.org'
237 | heading "Extract Changelog from #{fname}"
238 |
239 | version = nil
240 |
241 | File.open(fname).each do |line|
242 | if mdata = line.match(/^\* (\d+\.\d+) until (\S.*\S)/)
243 | version = mdata[1]
244 | $changelog[version] = ''
245 | $changelog_until[version] = mdata[2]
246 | puts version
247 | else
248 | $changelog[version] += (line[2..-1] || '').rstrip + "\n" if version
249 | end
250 | end
251 |
252 | now = Time.now.strftime("%Y-%m-%d %a")[0..-2]
253 | $changelog_lisp.each_key do |version|
254 | $changelog[version] = $changelog_lisp[version]
255 | $changelog_until[version] ||= now
256 | end
257 | version_latest = $changelog.keys.max {|a,b| compare_semver(a,b)}
258 | $changelog_until[version_latest] = now
259 |
260 | $changelog.each_key do |version|
261 | brushup $changelog[version]
262 | end
263 | pp $changelog if $v
264 |
265 | end
266 |
267 |
268 | #
269 | # Tasks, that update files with collected information
270 | #
271 | desc 'Update Changelog with information from sourcefile'
272 | task :update_changelog => [:extract_changelog, :extract_version] do
273 |
274 | fname = 'ChangeLog.org'
275 | heading "Update #{fname}",true
276 | nname = fname + '.new'
277 |
278 | File.open(nname,'w') do |nfile|
279 | $changelog.keys.sort {|a,b| compare_semver(b,a)}.each do |version|
280 | nfile.puts "* #{version} until #{$changelog_until[version]}\n\n"
281 | $changelog[version].lines.each {|l| nfile.puts " #{l}".rstrip}
282 | nfile.puts "\n"
283 | end
284 | end
285 | accept fname,nname
286 |
287 | end
288 |
289 |
290 | desc 'Update Readme with information from sourcefile'
291 | task :update_readme => [:extract_changelog, :extract_version, :extract_commentary] do
292 |
293 | fname = 'README.org'
294 | heading "Update #{fname}",true
295 | nname = fname + ".new"
296 |
297 | toc = File.read(fname).lines.select {|l| l.start_with?('** ')}.map {|l| l[3..-1].chomp}
298 | unseen = Set.new([:version, :toc, :about, :changelog])
299 | tcvi = ' The current version is '
300 |
301 | File.open(nname,'w') do |nfile|
302 | File.open(fname) do |file|
303 |
304 | loop do
305 | line ||= file.gets
306 | break unless line
307 |
308 | # content of line will in any case written at bottom of loop, until then:
309 | # Write something else, replace content of line or leave as is
310 |
311 | if line.start_with?(tcvi)
312 | heading 'Version'
313 | line = tcvi + $version_lisp + '.'
314 | unseen.delete(:version)
315 | end
316 |
317 | if line.start_with?('** Table of Contents')
318 | heading 'Table of contents'
319 | nfile.puts line + "\n"
320 | toc.drop(1).each {|t| nfile.puts " - [[##{t.downcase.tr(' ','-')}][#{t}]]"}
321 | nfile.puts "\n"
322 | line = forward_to(file,'** ')
323 | unseen.delete(:toc)
324 | end
325 |
326 | if line.start_with?('** About this Package')
327 | heading 'Commentary'
328 | nfile.puts line + "\n"
329 | write_as_org nfile,3,$commentary_lisp
330 | line = forward_to(file,'** ')
331 | unseen.delete(:about)
332 | end
333 |
334 | if line.start_with?('** Latest Change Log')
335 | heading 'Latest Change log'
336 | nfile.puts line + "\n See ChangeLog.org for older entries.\n\n"
337 | write_as_org nfile,3,$changelog_lisp
338 | line = forward_to(file,'* ')
339 | unseen.delete(:changelog)
340 | end
341 |
342 | # now write whatever current content of line is
343 | nfile.puts line if line
344 | end
345 |
346 | end
347 | end
348 | abort "Did not see #{unseen.inspect} in #{fname}" if unseen.length > 0
349 |
350 | accept fname,nname
351 |
352 | end
353 |
354 |
355 | desc 'Update sourcefile with information from sourcefile'
356 | task :update_lisp => [:extract_changelog, :extract_version, :extract_commentary] do
357 |
358 | fname = $conf[:source]
359 | heading "Update #{fname}",true
360 | nname = fname + ".new"
361 |
362 | unseen = Set.new([:version, :commentary])
363 | tiv = 'This is version'
364 |
365 | File.open(nname,'w') do |nfile|
366 | File.open(fname) do |file|
367 |
368 | loop do
369 | line ||= file.gets
370 | break unless line
371 |
372 | # content of line will in any case written at bottom of loop, until then:
373 | # Write something else, replace content of line or leave as is
374 |
375 | if line.start_with?("(defvar #{$conf[:package]}-version")
376 | heading 'Version'
377 | line.sub!(/\d+\.\d+\.\d+/,$version_lisp)
378 | unseen.delete(:version)
379 | end
380 |
381 | if line['For Rake: Insert here']
382 | heading 'Commentary'
383 | nfile.write line
384 | first = true
385 | $conf[:pieces_for_docstring].each do |piece|
386 | abort "ERROR: Configuration item 'pieces_for_docstring' from $conf[:file] has unkonwn docstring-piece #{piece}" unless $commentary_lisp[piece]
387 | nfile.print first ? " \"" : "\n\n#{piece}:\n\n"
388 | nfile.print $commentary_lisp[piece]
389 | first = false
390 | end
391 | forward_to(file,tiv)
392 | line = "\n\n#{tiv} #{$version_lisp} of #{$conf[:source]}.\n"
393 | unseen.delete(:commentary)
394 | end
395 |
396 | # now write whatever current content of line is
397 | nfile.puts line if line
398 | end
399 |
400 | end
401 | end
402 | abort "Did not see #{unseen.inspect} in #{fname}" if unseen.length > 0
403 |
404 | accept fname,nname
405 |
406 | end
407 |
408 |
409 | desc 'Describe building process'
410 | task :h => [:extract_version] do
411 | within = false
412 | doc = File.open(%x{git rev-parse --show-toplevel}.chomp + '/README.org').each do |line|
413 | within = line.include?('Preparing') if line.start_with?('*')
414 | print line if within
415 | end
416 | puts "Version from lisp: #{$version_lisp}"
417 | puts "Latest tag from git: " + %x(git describe).chomp
418 | end
419 |
420 |
421 | desc 'Run all tests from directory test'
422 | task :test => [:update_rake] do
423 |
424 | heading "Run tests",true
425 | command = <<-END.lines.map {|l| l.strip!}.join(' ')
426 | emacs
427 | --no-init-file
428 | --no-site-file
429 | --no-site-lisp
430 | --eval "(set-variable 'make-backup-files nil)"
431 | --eval "(set-variable 'auto-save-default nil)"
432 | --eval "(set-variable 'create-lockfiles nil)"
433 | --eval "(menu-bar-mode -1)"
434 | --eval "(setq load-prefer-newer t)"
435 | --eval "(add-to-list 'load-path \\\".\\\")"
436 | --eval "(setq package-user-dir \\\"#{File.dirname(__FILE__)+"/elpa"}\\\")"
437 | --eval "(setq base-dir \\\"#{File.dirname(__FILE__)}\\\")"
438 | --eval "(package-initialize)"
439 | --load ert
440 | --load #{File.dirname(__FILE__)+"/test/"+$conf[:testfile]}
441 | test/#{$conf[:testfile]}
442 | #{$conf[:source]}
443 | --eval "(ert-run-tests-batch-and-exit)"
444 | --batch
445 | END
446 |
447 | puts command
448 | at_summary = false
449 | Open3.popen2e(command) do |stdin, stdout_stderr, status_thread|
450 | stdout_stderr.each_line do |line|
451 | at_summary = true if line.match?(/^Ran \d+ /)
452 | if at_summary
453 | puts line
454 | elsif line.lstrip.start_with?('passed')
455 | heading line
456 | elsif line.lstrip.start_with?('FAILED')
457 | heading line,false,true
458 | elsif $v
459 | puts line
460 | end
461 | end
462 | abort "ERROR: Command ended with error.\nRerun with '-v' for details." unless status_thread.value.success?
463 | end
464 |
465 | end
466 |
467 |
468 | desc 'Update all files'
469 | task :update => [:update_changelog, :update_readme, :update_lisp, :test] do
470 | end
471 |
472 |
473 | desc 'Update all files and run tests'
474 | task :default => [:update, :test] do
475 | end
476 |
--------------------------------------------------------------------------------
/images/screenshot1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marcIhm/org-id-cleanup/512656722edd1cb8a4cc0d01efa01cdad23abeb6/images/screenshot1.png
--------------------------------------------------------------------------------
/org-id-cleanup.el:
--------------------------------------------------------------------------------
1 | ;;; org-id-cleanup.el --- Interactively find, present and maybe delete unused IDs of org-id -*- lexical-binding: t; -*-
2 |
3 | ;; Copyright (C) 2020-2023 Free Software Foundation, Inc.
4 |
5 | ;; Author: Marc Ihm
6 | ;; URL: https://github.com/marcIhm/org-id-cleanup
7 | ;; Version: 1.7.1
8 | ;; Package-Requires: ((org "9.3") (dash "2.12") (emacs "26.3"))
9 |
10 | ;; This file is not part of GNU Emacs.
11 |
12 | ;;; License:
13 |
14 | ;; This program is free software; you can redistribute it and/or modify
15 | ;; it under the terms of the GNU General Public License as published by
16 | ;; the Free Software Foundation; either version 3, or (at your option)
17 | ;; any later version.
18 | ;;
19 | ;; This program is distributed in the hope that it will be useful,
20 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 | ;; GNU General Public License for more details.
23 | ;;
24 | ;; You should have received a copy of the GNU General Public License
25 | ;; along with GNU Emacs. If not, see .
26 | ;;
27 |
28 | ;;; Commentary:
29 |
30 | ;; Purpose:
31 | ;;
32 | ;; Interactively find and clean up unused IDs of org-id.
33 | ;; The term 'unused' refers to IDs, that have been created by org-id
34 | ;; regularly, but are now no longer referenced from anywhere within in org.
35 | ;; This might e.g. happen by deleting a link, that once referenced such an id.
36 | ;;
37 | ;; Normal usage of org-id does not lead to a lot of such unused IDs, and
38 | ;; org-id does not suffer much from them.
39 | ;;
40 | ;; However, some usage patterns or packages (like org-working-set) may
41 | ;; produce a larger number of such unused IDs; in such cases it might be
42 | ;; helpful to clean up with org-id-cleanup.
43 | ;;
44 | ;; Setup:
45 | ;;
46 | ;; org-id-cleanup should be installed with package.el or use-package
47 | ;;
48 |
49 | ;;; Change Log:
50 |
51 | ;; Version 1.7
52 | ;;
53 | ;; - Compute differences to previous invocation and offer files to be
54 | ;; added back
55 | ;; - Show headings along with IDs for deletion
56 | ;;
57 | ;; Version 1.6
58 | ;;
59 | ;; - Restructured instructions
60 | ;; - Various clarifications
61 | ;;
62 | ;; Version 1.5
63 | ;;
64 | ;; - Scan more files for IDs
65 | ;; - Write list of files to log
66 | ;; - Offer to revert all changes
67 | ;; - More hints
68 | ;;
69 | ;; Version 1.4
70 | ;;
71 | ;; - Clarification regarding archives
72 | ;; - Rely on org-id-files
73 | ;; - Refactoring
74 | ;;
75 | ;; Version 1.3
76 | ;;
77 | ;; - Write a log of deleted IDs
78 | ;;
79 | ;; Version 1.2
80 | ;;
81 | ;; - Adding tests
82 | ;; - Preparing for melpa
83 | ;;
84 | ;; Version 1.1
85 | ;;
86 | ;; - Respecting attachments
87 | ;; - Refactoring
88 | ;;
89 | ;; Version 1.0
90 | ;;
91 | ;; - Initial Version
92 | ;;
93 |
94 | ;;; Code:
95 |
96 | (require 'org)
97 | (require 'button)
98 | (require 'org-attach)
99 | (require 'dash)
100 | (require 'subr-x)
101 | (require 'org-id)
102 |
103 | ;; Version of this package
104 | (defvar org-id-cleanup-version "1.7.1" "Version of `org-working-set', format is major.minor.bugfix, where \"major\" are incompatible changes and \"minor\" are new features.")
105 |
106 | (defvar org-id-cleanup--assistant-buffer-name "*Assistant for deleting IDs*")
107 | (defvar org-id-cleanup--all-steps '(save backup complete-files review-files collect-ids review-ids cleanup-ids save-again) "List of all supported steps.")
108 | (defvar org-id-cleanup--current-step nil "Current step in assistant.")
109 | (defvar org-id-cleanup--files nil "List of all files to be scanned while cleaning ids.")
110 | (defvar org-id-cleanup--unref-unattach-ids nil "List of IDs not referenced from files and not having attachments. Candidates for deletion.")
111 | (defvar org-id-cleanup--num-deleted-ids 0 "Number of IDs deleted.")
112 | (defvar org-id-cleanup--num-attach 0 "Number of IDs that are referenced by their attachment directory only.")
113 | (defvar org-id-cleanup--num-all-ids 0 "Number of all IDs.")
114 | (defvar org-id-cleanup--log-file-name (concat (file-name-directory org-id-locations-file) "org-id-cleanup-log-of-deletions.org")
115 | "Filename for log buffer; derived from value of 'org-id-locations-file'.")
116 | (defvar org-id-cleanup--log-buffer nil "Log buffer, once opened.")
117 |
118 | ;; User-visible function and dispatch
119 | (defun org-id-cleanup ()
120 | ;; Do NOT edit the part of this help-text before version number. It will
121 | ;; be overwritten with Commentary-section from beginning of this file.
122 | ;; Editing after version number is fine.
123 | ;;
124 | ;; For Rake: Insert here
125 | "Interactively find and clean up unused IDs of org-id.
126 | The term 'unused' refers to IDs, that have been created by org-id
127 | regularly, but are now no longer referenced from anywhere within in org.
128 | This might e.g. happen by deleting a link, that once referenced such an id.
129 |
130 | Normal usage of org-id does not lead to a lot of such unused IDs, and
131 | org-id does not suffer much from them.
132 |
133 | However, some usage patterns or packages (like org-working-set) may
134 | produce a larger number of such unused IDs; in such cases it might be
135 | helpful to clean up with org-id-cleanup.
136 |
137 | This is version 1.7.1 of org-id-cleanup.el.
138 |
139 | This assistant is the only interactive function of this package.
140 | Detailed explanations are shown in each step; please read them
141 | carefully and then operate the relevant buttons."
142 | (interactive)
143 | (org-id-cleanup--do 'save))
144 |
145 |
146 | (defun org-id-cleanup--do (go-to)
147 | "Do the work for `org-id-cleanup'.
148 | GO-TO the next step or one of symbols 'previous or 'next."
149 |
150 | ;; check arguments and compute next step
151 | (setq org-id-cleanup--current-step
152 | (if (member go-to '(previous next))
153 | (nth (+ (if (eq go-to 'next) +1 -1)
154 | (org-id-cleanup--step-to-num))
155 | org-id-cleanup--all-steps)
156 | go-to))
157 |
158 | ;; prepare buffer
159 | (pop-to-buffer-same-window (get-buffer-create org-id-cleanup--assistant-buffer-name))
160 | (setq buffer-read-only nil)
161 | (delete-other-windows)
162 | (erase-buffer)
163 | ;; breadcrumbs
164 | (dolist (st org-id-cleanup--all-steps)
165 | (insert (propertize (format "%s - " (symbol-name st))
166 | 'face (if (<= (org-id-cleanup--step-to-num st)
167 | (org-id-cleanup--step-to-num))
168 | 'org-agenda-dimmed-todo-face nil))))
169 | (backward-delete-char 3)
170 |
171 | (insert "\n\nThis assistant helps to clean up IDs from your org-files, it tries to remove only IDs, that are not referenced any longer.")
172 | (fill-paragraph)
173 | (insert "\n\n")
174 |
175 | ;; common controls
176 | (when (eq org-id-cleanup--current-step (cl-first org-id-cleanup--all-steps))
177 | (insert "It operates in steps, and explains what is going to happen in each step; it presents buttons, that when pressed execute the described action and take you to the next step. Pressing a button can be done either with the return-key or with the mouse.")
178 | (fill-paragraph)
179 | (insert "\n\n")
180 | (insert "The line of steps at the top of this window shows the progress within this assistant. No IDs will be deleted unless you confirm so in step 'cleanup-ids'")
181 | (fill-paragraph)
182 | (insert "\n\n\n"))
183 | (insert (format "Step %d of %s: %s"
184 | (1+ (org-id-cleanup--step-to-num))
185 | (length org-id-cleanup--all-steps)
186 | (symbol-name org-id-cleanup--current-step)))
187 | (when (> (org-id-cleanup--step-to-num) 0)
188 | (insert (propertize " (or back to " 'face 'org-agenda-dimmed-todo-face))
189 | (insert-button
190 | (propertize
191 | (symbol-name (nth (1- (org-id-cleanup--step-to-num)) org-id-cleanup--all-steps))
192 | 'face 'org-agenda-dimmed-todo-face) 'action
193 | (lambda (_) (org-id-cleanup--do 'previous)))
194 | (insert (propertize ")" 'face 'org-agenda-dimmed-todo-face)))
195 | (insert "\n\n\n")
196 |
197 | ;; dispatch according to step
198 | (funcall (intern (concat "org-id-cleanup--step-" (symbol-name org-id-cleanup--current-step))))
199 |
200 | ;; finish buffer before leaving it to the user to press any buttons therein; see individual steps
201 | (recenter -1)
202 | (message "Please read comments and instructions and proceed by clicking the appropriate buttons.")
203 | (setq buffer-read-only t))
204 |
205 |
206 | ;; Individual steps
207 | (defun org-id-cleanup--step-save ()
208 | "Step from `org-id-cleanup--do'."
209 |
210 | (let (pt)
211 | (insert "You need to save all org buffers and update org-id locations: ")
212 |
213 | (insert-button
214 | "go" 'action
215 | (lambda (_)
216 | (goto-char (point-max))
217 | (let ((inhibit-read-only t))
218 | (insert "\n\n\nSaving buffers ... ")
219 | (redisplay)
220 | (org-save-all-org-buffers)
221 | (insert "done\nUpdating id locations ... ")
222 | (redisplay)
223 | (org-id-update-id-locations))
224 | ;; continue with next step
225 | (org-id-cleanup--do 'next)))
226 |
227 | (setq pt (point))
228 | (when (fboundp 'org-working-set)
229 | (insert "\n\n\nNote: You have loaded the package org-working-set. If you use it regularly you may want to truncate its journal to a reasonable length (e.g. 90 days back), because it keeps links to all nodes that have been in your working-set in the past; that way the related IDs can not be deleted, because they are referenced at least once.")
230 | (fill-paragraph))
231 | (goto-char pt)))
232 |
233 |
234 | (defun org-id-cleanup--step-backup ()
235 | "Step from `org-id-cleanup--do'."
236 |
237 | (if (not org-id-track-globally)
238 | (insert "\n\nThe variable `org-id-track-globally' is not set, therefore this assistant cannot be useful and will not continue.\n")
239 |
240 | (insert "Please make sure that you have a backup, if something goes wrong !\nIf you have your org-files in git, consider a commit.\n\n\nThis assistant cannot do this for you; so please come back when done\nand press this ")
241 | (insert-button "button" 'action
242 | (lambda (_) (org-id-cleanup--do 'next)))))
243 |
244 |
245 | (defun org-id-cleanup--step-complete-files ()
246 | "Step from `org-id--cleanup-do'."
247 | (let* ((head-of-files "--- start of extra files to be scanned ---")
248 | (tail-of-files "--- end of extra files to be scanned ---")
249 | (text-point-files (org-id-cleanup--get-latest-log-heading))
250 | (files-was (nth 2 text-point-files))
251 | (preset-files
252 | (org-id-cleanup--normalize-files
253 | ;; this mirrors the list of files constructed in org-id-update-id-locations
254 | (org-agenda-files t org-id-search-archives)
255 | (unless (symbolp org-id-extra-files)
256 | org-id-extra-files)
257 | org-id-files
258 | user-init-file
259 | custom-file))
260 | pt pt2 was-but-not-is)
261 | (forward-line -2)
262 | (insert (propertize "Scroll down for continue-button.\n\n" 'face 'org-agenda-dimmed-todo-face))
263 | (setq pt2 (point))
264 | (insert (concat "Complete the list of "
265 | (propertize (number-to-string (length preset-files)) 'face 'bold)
266 | " files (which is generated by org-agenda-files), that will be scanned and might be changed:\n\n"))
267 | (org-id-cleanup--insert-files preset-files)
268 | (insert "\n\nSee the end of this screen to learn, what files should be present in the list above.")
269 |
270 | (insert "\n\n\nIf you want more files or directories to be scanned,\nplease add them to the list of extra files below: ")
271 | (insert-button
272 | "browse" 'action
273 | (lambda (_)
274 | (let ((file (read-file-name "Choose a single files or a whole directory: " org-directory))
275 | (inhibit-read-only t)
276 | pt)
277 | (when file
278 | (goto-char (point-min))
279 | (search-forward head-of-files)
280 | (forward-line 1)
281 | (setq pt (point))
282 | (search-forward tail-of-files)
283 | (forward-line 0)
284 | (insert file "\n")
285 | (add-text-properties pt (point) '(inhibit-read-only t))))))
286 | (insert "\n\n" head-of-files "\n")
287 | (setq pt (point))
288 | (setq was-but-not-is (-difference files-was preset-files))
289 | (mapc (lambda (x) (insert (format "%s\n" x))) was-but-not-is)
290 | (add-text-properties pt (point) '(inhibit-read-only t))
291 | (insert tail-of-files "\n")
292 | (insert (propertize "(usual editing commands (e.g. C-k) apply.)\n" 'face 'org-agenda-dimmed-todo-face))
293 | (when was-but-not-is
294 | (insert (propertize "\nPlease note: " 'face 'org-warning))
295 | (insert "The list of extra files above has been prepopulated with all the files, that have been scanned in the previous invocation but have not found to be scanned any longer. If you keep them among extra files, they will be scanned again, but you may remove them, e.g. if they do not contain any IDs or have been removed from the filesystem.")
296 | (fill-paragraph)
297 | (insert (format "\nThe headline of the previous invocation was (click to visit):\n\n "))
298 | (org-id-cleanup--insert-button-browse-previous text-point-files)
299 | (insert "\n"))
300 |
301 | (insert "\n\nAfter that, you may ")
302 | (insert-button
303 | "continue" 'action
304 | (lambda (_)
305 | ;; change global state
306 | (setq org-id-cleanup--files
307 | (org-id-cleanup--normalize-files
308 | preset-files
309 | (org-id-cleanup--collect-extra-files head-of-files)))
310 | ;; continue with next step
311 | (org-id-cleanup--do 'next)))
312 | (setq pt (point))
313 |
314 | (insert "\n\n\n")
315 | (insert (propertize "What files should be present in the list above ?" 'face 'org-level-2))
316 | (insert "\n\nThe list should include all files that:\n\n"
317 | " - Contain nodes with IDs (which will be removed, if not referenced from anywhere)\n"
318 | " - Have references or links to IDs (which protect those IDs from being removed)\n\n"
319 | "(of course, most of your org-files may contain both)")
320 | (insert "\n\nPlease note: If the list of files and directories is incomplete, this might lead to IDs being removed, that are still referenced from a file that is missing in the list.")
321 | (fill-paragraph)
322 |
323 | (insert "\n\nIDs may also appear in lisp-files, so your user init file has already been added. But if you use IDs from within other lisp-code, this will not be noticed. However, to protect such IDs once and for all, it is enough to list them anywhere within your org-files (e.g. below a dedicated heading 'protected IDs'). ")
324 | (fill-paragraph)
325 |
326 | (insert "\n\nMoreover, you might have the habit of using IDs completely outside of org (e.g. in your calendar); such use cannot be noticed by this package, and if there are no other references from within org, these IDs will be deleted. But again, to protect those, it is enough to list them anywhere within your org-files.")
327 | (fill-paragraph)
328 |
329 | (insert "\n\nPlease note, that regarding archives, this assistant relies on the handling configured for org-id in `org-id-search-archives'. Especially: If you do not search your archives for ids, references within your archives will not protect IDs from beeing removed.")
330 | (fill-paragraph)
331 | (goto-char pt2)))
332 |
333 |
334 | (defun org-id-cleanup--step-collect-ids ()
335 | "Step from `org-id--cleanup-do'."
336 | (insert (concat "Now the relevant "
337 | (propertize (number-to-string (length org-id-cleanup--files)) 'face 'bold)
338 | " files will be scanned for IDs.\n\n"))
339 | (insert "Any IDs, that are used for attachment directories will be kept; the same is true,\nif the node is merely tagged as having an attachment.\n\n")
340 | (insert "From now on, please refrain from leaving this assistant to create links to IDs, because they would not be taken into account any more.")
341 | (fill-paragraph)
342 | (insert "\n\n\nScan files for IDs and ")
343 |
344 | (insert-button "continue" 'action 'org-id-cleanup--action-collect-ids))
345 |
346 |
347 | (defun org-id-cleanup--step-review-files ()
348 | "Step from `org-id--cleanup-do'."
349 | (let ((text-point-files (org-id-cleanup--get-latest-log-heading))
350 | pt)
351 | (forward-line -2)
352 | (insert (propertize "Scroll down for continue-button.\n\n" 'face 'org-agenda-dimmed-todo-face))
353 | (setq pt (point))
354 | (insert (concat "Review the list of "
355 | (propertize (number-to-string (length org-id-cleanup--files)) 'face 'bold)
356 | " files that will be scanned; the org-files among them might be changed:\n\n"))
357 | (org-id-cleanup--insert-files org-id-cleanup--files)
358 | (insert "\n\nThis list contains any extra files or directories you might have added in the previous step.")
359 | (insert "\n\n\nIf you want to compare this list with previous invocations, you may browse:\n\n ")
360 | (org-id-cleanup--insert-button-browse-previous text-point-files)
361 | (insert "\n\n\nWhen satisfied, ")
362 | (insert-button
363 | "continue" 'action
364 | (lambda (_)
365 | ;; continue with next step
366 | (org-id-cleanup--do 'next)))
367 | (insert (propertize "\n\n\nOr, to add more files, go " 'face 'org-agenda-dimmed-todo-face))
368 | (insert-button
369 | (propertize "back" 'face 'org-agenda-dimmed-todo-face) 'action
370 | (lambda (_) (org-id-cleanup--do 'previous)))
371 | (goto-char pt)))
372 |
373 |
374 | (defun org-id-cleanup--step-review-ids ()
375 | "Step from `org-id--cleanup-do'."
376 | (let ((head-of-ids "--- List of IDs to be deleted ---")
377 | pt pt2 pct)
378 | (setq pct (* 100 (/ (float (length org-id-cleanup--unref-unattach-ids)) org-id-cleanup--num-all-ids)))
379 | (insert (format "Find below the list of IDs (%d out of %d) that will be deleted; pressing TAB on an id will show the respective node. To provide context, the associated headings are shown (but of course, will not be deleted)." (length org-id-cleanup--unref-unattach-ids) org-id-cleanup--num-all-ids))
380 | (fill-paragraph)
381 | (insert (format "\n%d IDs are not in the list and will be kept, because they have associated attachments.\n\n" org-id-cleanup--num-attach))
382 | (insert "You may remove IDs from the list as you like to keep them from being deleted.\nUsual editing commands (e.g. C-k) apply.")
383 | (insert (format "\n\nThe list below contains %.1f %% of all IDs; if this is more than expected, the list of files to be scanned might have been incomplete and you may want to " pct))
384 | (insert-button "add files to be scanned" 'action
385 | (lambda (_) (org-id-cleanup--do 'complete-files)))
386 | (insert " for references to IDs.")
387 | (fill-paragraph)
388 | (insert "\n\nIf satisfied, ")
389 |
390 | (insert-button
391 | "continue" 'action
392 | (lambda (_)
393 | (local-unset-key (kbd "")) ; tab is no longer needed in next step
394 | ;; change global state
395 | (setq org-id-cleanup--unref-unattach-ids (org-id-cleanup--collect-ids head-of-ids))
396 | ;; continue with next step
397 | (org-id-cleanup--do 'next)))
398 |
399 | (setq pt (point))
400 | (insert (propertize "\n\ndeletion will not happen yet." 'face 'org-agenda-dimmed-todo-face))
401 | (insert "\n\n\n" head-of-ids "\n")
402 | (setq pt2 (point))
403 | (dolist (id org-id-cleanup--unref-unattach-ids)
404 | (insert id " "
405 | (save-window-excursion
406 | (org-id-goto id)
407 | (propertize (or (org-get-heading) "?") 'face 'org-agenda-dimmed-todo-face))
408 | "\n"))
409 |
410 | (add-text-properties pt2 (point) '(inhibit-read-only t))
411 | (goto-char pt)
412 | (local-set-key (kbd "") 'org-id-cleanup--peek-into-id)))
413 |
414 |
415 | (defun org-id-cleanup--step-cleanup-ids ()
416 | "Step from `org-id--cleanup-do'."
417 | (let (pt)
418 | (insert "Please make sure, that you have not manually created new links referencing any IDs while the last two steps of this assistant were active.")
419 | (fill-paragraph)
420 | (insert
421 | (format "\n\nFor your reference, a log of all changes will be appended to %s.\n" org-id-cleanup--log-file-name)
422 | "This log will contain sufficient information (id, filename, point and outline path) to manually restore selected IDs later; you may browse it before saving your files in the last step.")
423 | (fill-paragraph)
424 | (insert "\n\n\n")
425 | (insert (propertize (format " >>> To REMOVE %s IDs out of %d UNCONDITIONALLY, press this " (length org-id-cleanup--unref-unattach-ids) org-id-cleanup--num-all-ids) 'face 'org-warning))
426 |
427 | (insert-button (propertize "button" 'face 'org-warning) 'action 'org-id-cleanup--action-cleanup-ids)
428 |
429 | (insert (propertize " <<<" 'face 'org-warning))
430 | (setq pt (point))
431 | (insert "\n\n\nOr, to review those IDs, go ")
432 | (insert-button
433 | "back" 'action
434 | (lambda (_) (org-id-cleanup--do 'previous)))
435 | (insert "\n")
436 | (goto-char pt)))
437 |
438 |
439 | (defun org-id-cleanup--step-save-again ()
440 | "Step from `org-id--cleanup-do'."
441 | (insert (format " Deleted %d IDs (out of %d).\n\n\n" org-id-cleanup--num-deleted-ids org-id-cleanup--num-all-ids))
442 | (insert (format "A log of all changes has been appended to %s\n" org-id-cleanup--log-file-name))
443 | (insert "\nYou may want to ")
444 | (insert-button
445 | "browse" 'action
446 | (lambda (_) (pop-to-buffer org-id-cleanup--log-buffer)))
447 | (insert " this file to see, what has been removed from your org-buffers but not saved yet.\n")
448 | (insert "If you want to discard those changes alltogether, you may ")
449 | (insert-button
450 | "revert all" 'action 'org-id-cleanup--action-revert)
451 | (insert " changed org buffers, as the files have not been saved yet.")
452 | (fill-paragraph)
453 |
454 | (insert "\n\n\nFinally, if satisfied, you should again save all org buffers, update id locations and save them: ")
455 |
456 | (insert-button
457 | "go" 'action
458 | (lambda (_)
459 | (let ((inhibit-read-only t))
460 | (goto-char (point-max))
461 | (insert "\n\n\nSaving buffers ... ")
462 | (redisplay)
463 | (org-save-all-org-buffers)
464 | (insert "done\nUpdating ids ... ")
465 | (redisplay)
466 | (org-id-update-id-locations org-id-cleanup--files)
467 | (insert "done\nSaving id locations ...")
468 | (redisplay)
469 | (org-id-locations-save)
470 |
471 | (insert "done\n\nAssistant done; you may kill this buffer ...\n")))))
472 |
473 |
474 | ;; Some steps have longer actions, that need their own function
475 | (defun org-id-cleanup--action-collect-ids (_)
476 | "Action for `org-id-cleanup--step-collect-ids.
477 | Collect ids not referenced from anywhere; the list of IDs will then be used in the next step"
478 | (let ((counters (make-hash-table :test 'equal))
479 | (scanned 0)
480 | (attach 0)
481 | ids pgreporter unref unref-unattach)
482 |
483 | ;; collect all IDs
484 | (maphash (lambda (id _) (unless (string= id "") (push id ids))) org-id-locations)
485 | (setq pgreporter (make-progress-reporter (format "Scanning %d files..." (length org-id-cleanup--files)) 1 (length org-id-cleanup--files)))
486 |
487 | ;; visit each file an count occurrences of IDs
488 | (dolist (file org-id-cleanup--files)
489 | (with-current-buffer (find-file-noselect file)
490 | (dolist (id ids)
491 | (goto-char (point-min))
492 | (while (search-forward id nil t)
493 | (cl-incf (gethash id counters 0)))))
494 | (progress-reporter-update pgreporter (cl-incf scanned)))
495 |
496 | ;; keep only IDs, that have appeared only once
497 | (maphash (lambda (id count) (if (eq count 1) (push id unref))) counters)
498 |
499 | ;; keep only IDs, that are not used in attachment dir
500 | (dolist (id unref)
501 | (let ((pos (org-id-find id)))
502 | (with-current-buffer (find-file-noselect (car pos))
503 | (goto-char (cdr pos))
504 | (if (or (and (fboundp 'org-attach-dir-from-id) ; only known in emacs 27
505 | (string= (org-attach-dir-from-id id) (org-attach-dir)))
506 | ;; assume id is used in attachments even if only last 12 chars match
507 | (cl-search (substring id -12) (org-attach-dir))
508 | (member "ATTACH" (org-get-tags))
509 | (member "attach" (org-get-tags))
510 | (member org-attach-auto-tag (org-get-tags)))
511 | (cl-incf attach)
512 | (push id unref-unattach)))))
513 |
514 | (progress-reporter-done pgreporter)
515 |
516 | ;; change global state
517 | (setq org-id-cleanup--unref-unattach-ids unref-unattach)
518 | (setq org-id-cleanup--num-all-ids (length ids))
519 | (setq org-id-cleanup--num-attach attach)
520 | ;; continue with next step
521 | (org-id-cleanup--do 'next)))
522 |
523 |
524 | (defun org-id-cleanup--action-cleanup-ids (_)
525 | "Action for `org-id-cleanup--step-cleanup-ids.
526 | Actually delete IDs."
527 |
528 | (let ((scanned 0)
529 | (inhibit-read-only t)
530 | pgreporter)
531 | ;; prepare
532 | (org-id-cleanup--open-log (length org-id-cleanup--unref-unattach-ids) org-id-cleanup--num-all-ids)
533 | (with-current-buffer org-id-cleanup--assistant-buffer-name
534 | (goto-char (point-max))
535 | (setq org-id-cleanup--num-deleted-ids 0)
536 | (insert "\n\nRemoving unused IDs ... ")
537 | (redisplay))
538 | (setq pgreporter (make-progress-reporter (format "Removing %d IDs..." (length org-id-cleanup--unref-unattach-ids)) 1 (length org-id-cleanup--unref-unattach-ids)))
539 |
540 | ;; loop of deletion
541 | (dolist (id org-id-cleanup--unref-unattach-ids)
542 | (pop-to-buffer (find-file-noselect (gethash id org-id-locations)))
543 | (goto-char (point-min))
544 | (search-forward id)
545 | ;; by prior computation, id should only appear once as the id property of a node; anything else is an internal error
546 | (unless (string= id (org-id-get))
547 | (error "Expected id of this node to be %s, but found %s" id (org-id-get)))
548 | ;; log first
549 | (org-id-cleanup--append-to-log id (buffer-file-name) (point) (-concat (org-get-outline-path) (list (nth 4 (org-heading-components)))))
550 | ;; then delete
551 | (org-delete-property "ID")
552 | (org-remove-empty-drawer-at (point))
553 | (cl-incf org-id-cleanup--num-deleted-ids)
554 | (progress-reporter-update pgreporter (cl-incf scanned)))
555 |
556 | (progress-reporter-done pgreporter)
557 | (org-id-cleanup--write-log)
558 | (sleep-for 1)
559 |
560 | ;; change global state
561 | (setq org-id-cleanup--unref-unattach-ids nil)
562 |
563 | ;; continue with next step
564 | (org-id-cleanup--do 'next)))
565 |
566 |
567 | (defun org-id-cleanup--action-revert (_)
568 | "Revert all changes done by assistant."
569 | (let ((num 0) fname txt)
570 | (dolist (buf (buffer-list))
571 | (setq fname (buffer-file-name buf))
572 | (when (and fname
573 | (buffer-modified-p buf)
574 | (file-readable-p fname)
575 | (member fname org-id-cleanup--files))
576 | (with-current-buffer buf
577 | (with-demoted-errors "Error: %S"
578 | (revert-buffer t t)
579 | (cl-incf num)))))
580 | (message "Reverted changes to %d files" num)
581 | (setq txt (with-temp-buffer
582 | (insert (format "Reverted changes to %d files at " num))
583 | (org-insert-time-stamp nil t t)
584 | (buffer-string)))
585 | (with-current-buffer org-id-cleanup--log-buffer
586 | (goto-char (point-max))
587 | (org-up-heading-all 1)
588 | (org-next-visible-heading 1)
589 | (insert " - " txt "\n\n"))
590 | (with-current-buffer org-id-cleanup--assistant-buffer-name
591 | (goto-char (point-max))
592 | (let ((inhibit-read-only t))
593 | (insert "\n\n" txt)))))
594 |
595 |
596 |
597 | ;; Some helper functions
598 | (defun org-id-cleanup--insert-files (files)
599 | "Insert given list of FILES into current buffer using full window width."
600 | (let ((tab-stop-list '(2 42 82)))
601 | (dolist (name files)
602 | (if (> (+ (indent-next-tab-stop (current-column))
603 | (length name))
604 | (- (window-width) 10))
605 | (insert "\n"))
606 | (tab-to-tab-stop)
607 | (insert name))))
608 |
609 |
610 | (defun org-id-cleanup--insert-button-browse-previous (tpf)
611 | "Insert a button to browse previous file."
612 | (insert-button
613 | (nth 0 tpf) 'action
614 | (lambda (_)
615 | (find-file-other-window org-id-cleanup--log-file-name)
616 | (with-selected-window (get-buffer-window (get-file-buffer org-id-cleanup--log-file-name))
617 | (org-set-startup-visibility)
618 | (goto-char (nth 1 tpf))
619 | (recenter 2)))))
620 |
621 |
622 | (defun org-id-cleanup--collect-extra-files (head)
623 | "Collect and return edited list of extra file.
624 | Argument HEAD is a marker-string that precedes the list of files in buffer."
625 | (let (file files)
626 | (goto-char (point-min))
627 | (search-forward head)
628 | (delete-trailing-whitespace (point) (point-max))
629 | (forward-line)
630 | (while (not (looking-at "---"))
631 | (setq file (buffer-substring (point) (point-at-eol)))
632 | (cond
633 | ((file-directory-p file)
634 | (setq files (append files (directory-files file t org-agenda-file-regexp))))
635 | ((file-exists-p file)
636 | (push file files))
637 | (t (error "%s is neither a file nor a directory; if it has been removed in the filesystem, you may remove it from this list too" file)))
638 | (forward-line))
639 | files))
640 |
641 |
642 | (defun org-id-cleanup--collect-ids (head)
643 | "Collect and return edited list of IDs from content of buffer.
644 | Argument HEAD is a marker-string, that precedes the list of ids in buffer."
645 | (let (id ids)
646 | (goto-char (point-min))
647 | (search-forward head)
648 | (delete-trailing-whitespace (point) (point-max))
649 | (forward-line)
650 | (while (not (= (point) (point-max)))
651 | (setq id (car (split-string (string-trim (buffer-substring (point-at-bol) (point-at-eol))))))
652 | (when (> (length id) 0)
653 | (unless (>= (length id) 12) ; 12 is the length of an org-generated id, uuidgen generates longer ids
654 | (error "Id %s does not seem to be a valid uuid" id))
655 | (push id ids))
656 | (forward-line))
657 | ids))
658 |
659 |
660 | (defun org-id-cleanup--peek-into-id ()
661 | "Show node with if of current line in other window."
662 | (interactive)
663 | (let* ((id (car (split-string (string-trim (buffer-substring (point-at-bol) (point-at-eol))))))
664 | (marker (org-id-find id t)))
665 | (unless marker
666 | (error "Cannot find ID %s" id))
667 | (delete-other-windows)
668 | (pop-to-buffer (marker-buffer marker) '(display-buffer-below-selected (inhibit-same-window . t)) t)
669 | (goto-char marker)
670 | (search-forward id)
671 | (beginning-of-line)
672 | (org-show-context 'tree)
673 | (recenter)
674 | (other-window 1)
675 | (message "Context of node with id %s" id)))
676 |
677 |
678 | (defun org-id-cleanup--step-to-num (&optional step)
679 | "Return number of current STEP (defaults to `org-id-cleanup--current-step') within list of all steps (counting from 0)."
680 | (unless step
681 | (setq step org-id-cleanup--current-step))
682 | (- (length org-id-cleanup--all-steps)
683 | (length (member step org-id-cleanup--all-steps))))
684 |
685 |
686 | (defun org-id-cleanup--normalize-files (&rest lists-or-strings)
687 | "Bring a LISTS-OR-STRINGS of filenames in standard form.
688 | By sorting, removing dups and mapping to true filename."
689 | (delete-consecutive-dups
690 | (sort
691 | (mapcar #'file-truename
692 | (-flatten lists-or-strings))
693 | 'string<)))
694 |
695 |
696 | (defun org-id-cleanup--get-latest-log-heading ()
697 | "Get latest heading from log buffer."
698 | (or (ignore-errors
699 | (save-window-excursion
700 | (save-current-buffer
701 | (find-file org-id-cleanup--log-file-name)
702 | (goto-char (point-max))
703 | (if (re-search-backward "^\* " nil t)
704 | (let (files)
705 | (ignore-errors
706 | (save-excursion
707 | (search-forward-regexp (org-item-re))
708 | (setq files (mapcar (lambda (x)
709 | (car (last (split-string (car x)))))
710 | (cdr (org-list-parse-list))))))
711 | (list (org-get-heading t t t t) (point) files))
712 | nil))))
713 | (list "no prior heading" 0 nil)))
714 |
715 |
716 | (defun org-id-cleanup--open-log (num-to-be-deleted num-all)
717 | "Open Log buffer.
718 | NUM-TO-BE-DELETED and NUM-ALL used for explanation."
719 | (setq org-id-cleanup--log-buffer (find-file-noselect org-id-cleanup--log-file-name))
720 | (with-current-buffer org-id-cleanup--log-buffer
721 | (goto-char (point-max))
722 | (org-mode)
723 | (insert "\n\n* org-id-cleanup at ")
724 | (org-insert-time-stamp nil t t)
725 | (insert (format " scanned %d files and deleted %d IDs out of %d\n" (length org-id-cleanup--files) num-to-be-deleted num-all))
726 | (insert "\n** List of files scanned\n\n")
727 | (let ((i 0))
728 | (mapc (lambda (name) (insert (format " - %d : %s\n" (cl-incf i) name))) (sort org-id-cleanup--files 'string<)))
729 | (insert "\n** List of IDs deleted\n")
730 | (save-buffer)))
731 |
732 |
733 | (defun org-id-cleanup--append-to-log (id filename point path)
734 | "Append to Log buffer.
735 | ID, FILENAME, POINT and PATH specify detailed location of the id deleted."
736 | (with-current-buffer org-id-cleanup--log-buffer
737 | (insert "\n")
738 | (insert (format " - ID :: %s\n" id))
739 | (insert (format " - Filename :: %s\n" filename))
740 | (insert (format " - Point :: %d\n" point))
741 | (insert " - Path to node:\n")
742 | (dolist (ti path)
743 | (insert (format " - %s\n" ti)))
744 | (delete-blank-lines)))
745 |
746 |
747 | (defun org-id-cleanup--write-log ()
748 | "Write Log buffer to its file."
749 | (with-current-buffer org-id-cleanup--log-buffer
750 | (save-buffer)))
751 |
752 |
753 | (provide 'org-id-cleanup)
754 |
755 | ;; Local Variables:
756 | ;; fill-column: 75
757 | ;; comment-column: 50
758 | ;; End:
759 |
760 | ;;; org-id-cleanup.el ends here
761 |
--------------------------------------------------------------------------------
/rake_config.yml:
--------------------------------------------------------------------------------
1 | source: org-id-cleanup.el
2 | package: org-id-cleanup
3 | required_pieces_commentary:
4 | - Purpose
5 | - Setup
6 | pieces_for_docstring:
7 | - Purpose
8 | testfile: oidclpt.el
9 |
10 | # Maybe override this in rake_config_no_git.yml
11 | rake_be_symlink: false
12 |
--------------------------------------------------------------------------------
/test/.nosearch:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marcIhm/org-id-cleanup/512656722edd1cb8a4cc0d01efa01cdad23abeb6/test/.nosearch
--------------------------------------------------------------------------------
/test/oidclpt.el:
--------------------------------------------------------------------------------
1 | ;;; oidclpt.el --- Regression Tests for org-id-cleanup.el
2 |
3 | ;; Copyright (C) 2020 Free Software Foundation, Inc.
4 |
5 | ;; Author: Marc Ihm <1@2484.de>
6 | ;; Keywords: outlines, regression-tests, elisp
7 | ;; Requires: org, org-id-cleanup
8 | ;; Version: 0.0.1
9 |
10 | ;; This file is not part of GNU Emacs.
11 |
12 | ;;; License:
13 |
14 | ;; This program is free software; you can redistribute it and/or modify
15 | ;; it under the terms of the GNU General Public License as published by
16 | ;; the Free Software Foundation; either version 3, or (at your option)
17 | ;; any later version.
18 | ;;
19 | ;; This program is distributed in the hope that it will be useful,
20 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 | ;; GNU General Public License for more details.
23 | ;;
24 | ;; You should have received a copy of the GNU General Public License
25 | ;; along with GNU Emacs. If not, see .
26 |
27 | ;;; Commentary:
28 |
29 | ;; Purpose:
30 | ;;
31 | ;; Regression tests for package org-id-cleanup.el.
32 | ;;
33 | ;; Setup:
34 | ;;
35 | ;; None required
36 | ;;
37 | ;;
38 | ;;
39 | ;; Further reading:
40 | ;;
41 | ;; See org-id-cleanup.el, which is tested by this package
42 | ;;
43 |
44 | ;;; Code:
45 |
46 | (require 'org-id-cleanup)
47 | (require 'org-id)
48 | (require 'cl-lib)
49 | (require 'ert)
50 | (require 'dash)
51 |
52 | (defvar oidclpt-ert-work-file (concat temporary-file-directory "oidclpt-ert-work.org"))
53 | (defvar oidclpt-attachment (concat temporary-file-directory "oidclpt-attachment"))
54 | (defvar oidclpt-work-buffer nil)
55 | (defvar oidclpt-ids '(""
56 | "53e15dce-6f28-4674-bd65-e63b516d97ac"
57 | "87512329-a204-47e5-b38c-1b22838b6f7d"
58 | "b77473f3-dba0-4b4f-9db7-3ba095d12de4"
59 | "2a3d87d0-9ad0-416b-aa22-dea96fede8b7"))
60 |
61 | ;;
62 | ;; All tests
63 | ;;
64 |
65 | (ert-deftest oidclpt-test-aaa-test-test-setup ()
66 | (oidclpt-with-test-setup
67 | (message "Testing test setup")))
68 |
69 |
70 | (ert-deftest oidclpt-test-assistant-from-start-to-end ()
71 | (oidclpt-with-test-setup
72 | (let (ids)
73 | (org-id-cleanup)
74 | (oidclpt-press-button "go")
75 | (oidclpt-press-button "press this button")
76 | (goto-char (point-min))
77 | (search-forward "--- start")
78 | (end-of-line)
79 | (setq buffer-read-only nil)
80 | (insert "\n")
81 | (insert oidclpt-ert-work-file)
82 | (dotimes (_ 3)
83 | (oidclpt-press-button "continue"))
84 | (setq ids (oidclpt--collect-ids-from-list "--- List of"))
85 | (should (= (length ids) 1))
86 | (should (string= (car (split-string (nth 0 ids))) (nth 3 oidclpt-ids)))
87 | (oidclpt-press-button "continue")
88 | (oidclpt-press-button "button")
89 | (oidclpt-press-button "go")
90 | (goto-char (point-min))
91 | (search-forward "Assistant done;")
92 | (with-current-buffer oidclpt-work-buffer
93 | (setq ids (oidclpt--collect-ids-from-properties)))
94 | (should (= (length ids) 3))
95 | (should (not (-difference (list "" (nth 3 oidclpt-ids))
96 | (-difference oidclpt-ids ids))))
97 | (with-current-buffer org-id-cleanup--log-buffer
98 | (goto-char (point-min))
99 | (search-forward (nth 3 oidclpt-ids))))))
100 |
101 |
102 | ;;
103 | ;; Helper functions
104 | ;;
105 |
106 | (defmacro oidclpt-with-test-setup (&rest body)
107 | "Execute body within test setup"
108 | (declare (indent 0) (debug t))
109 | `(progn
110 | (oidclpt-setup-test)
111 | (unwind-protect
112 | (progn ,@body)
113 | (oidclpt-teardown-test))))
114 |
115 |
116 | (defun oidclpt-setup-test ()
117 | (interactive)
118 | ;; erase log file of deletions
119 | (setq org-id-cleanup--log-file-name (concat temporary-file-directory "oidclpt-cleanup-log-of-deletions.org"))
120 | (find-file org-id-cleanup--log-file-name)
121 | (erase-buffer)
122 | (save-buffer)
123 | ;; remove any left over buffers
124 | (oidclpt-remove-work-buffers)
125 | ;; create them new
126 | (oidclpt-create-work-buffer)
127 | (switch-to-buffer oidclpt-work-buffer)
128 | (basic-save-buffer)
129 | (org-agenda-file-to-front oidclpt-ert-work-file)
130 | (switch-to-buffer oidclpt-work-buffer)
131 | (org-cycle '(64))
132 | (delete-other-windows)
133 | (end-of-buffer))
134 |
135 |
136 | (defun oidclpt-teardown-test ()
137 | (interactive)
138 | (with-current-buffer oidclpt-work-buffer
139 | (set-buffer-modified-p nil)
140 | (basic-save-buffer))
141 | (org-remove-file oidclpt-ert-work-file))
142 |
143 |
144 | (defun oidclpt-remove-work-buffers ()
145 | "Remove any left over work buffers"
146 | (let ((b (get-buffer "oidclpt-ert-work.org")))
147 | (when b
148 | (with-current-buffer b
149 | (set-buffer-modified-p nil))
150 | (kill-buffer b)))
151 | (setq oidclpt-work-buffer nil))
152 |
153 |
154 | (defun oidclpt-press-button (text)
155 | "Press the first button with this text"
156 | (let (found)
157 | (goto-char (point-min))
158 | (while (not found)
159 | (search-forward text)
160 | (backward-char)
161 | (when (overlays-at (point))
162 | (push-button)
163 | (setq found t)))))
164 |
165 | ;;
166 | ;; Test data
167 | ;;
168 |
169 | (defun oidclpt-create-work-buffer ()
170 | (unless oidclpt-work-buffer
171 | (setq oidclpt-work-buffer (find-file-noselect oidclpt-ert-work-file)))
172 | (with-current-buffer oidclpt-work-buffer
173 | (setq buffer-save-without-query t)
174 | (auto-save-mode t)
175 | (if (file-exists-p buffer-auto-save-file-name)
176 | (delete-file buffer-auto-save-file-name))
177 | (erase-buffer)
178 | (insert
179 | (format "
180 | * eins
181 | :PROPERTIES:
182 | :ID: %s
183 | :END:
184 |
185 | This node has an attachment, but the attach-tag has been removed.
186 |
187 | * zwei
188 | :PROPERTIES:
189 | :ID: %s
190 | :END:
191 |
192 | * drei
193 | :PROPERTIES:
194 | :ID: %s
195 | :END:
196 |
197 | Reference to zwei protects the id of zwei from beeing deleted: %s
198 |
199 | But itself, this is the only node with an ID that should be deleted.
200 |
201 | * vier :ATTACH:
202 | :PROPERTIES:
203 | :ID: %s
204 | :END:
205 |
206 | This node only has the attach-tag, but no attachment.
207 |
208 | "
209 | (nth 1 oidclpt-ids)
210 | (nth 2 oidclpt-ids)
211 | (nth 3 oidclpt-ids)
212 | (nth 2 oidclpt-ids)
213 | (nth 4 oidclpt-ids)))
214 |
215 | (org-mode)
216 | ;; add attachment
217 | (goto-char (point-min))
218 | (search-forward "eins")
219 | (save-excursion
220 | (find-file oidclpt-attachment)
221 | (erase-buffer)
222 | (insert "Content of attachment\n")
223 | (basic-save-buffer))
224 | (save-excursion ; do not merge those two save-excursions
225 | (org-attach-new oidclpt-attachment))
226 | (search-forward ":ATTACH:")
227 | (backward-delete-char 8)))
228 |
229 |
230 | (defun oidclpt--collect-ids-from-list (head)
231 | "Collect and return IDs from list at end of buffer."
232 | (let (ids)
233 | (goto-char (point-min))
234 | (search-forward head)
235 | (forward-line)
236 | (while (< (point) (point-max))
237 | (push (buffer-substring-no-properties (point) (point-at-eol)) ids)
238 | (forward-line))
239 | ids))
240 |
241 |
242 | (defun oidclpt--collect-ids-from-properties ()
243 | "Collect and return IDs from properties."
244 | (let (ids)
245 | (goto-char (point-min))
246 | (while (search-forward ":ID:" nil t)
247 | (push (string-trim (buffer-substring-no-properties (point) (point-at-eol)))
248 | ids))
249 | ids))
250 |
251 |
252 | (provide 'oidclpt)
253 |
254 | ;; Local Variables:
255 | ;; fill-column: 75
256 | ;; comment-column: 50
257 | ;; End:
258 |
259 | ;;; oidclpt.el ends here
260 |
--------------------------------------------------------------------------------