├── Rules ├── ruleBase.cpp ├── ruleText.cpp ├── ruleText.h ├── ruleDate.h ├── ruleReplace.h ├── rules.h ├── ruleFilename.h ├── ruleDir.h ├── ruleFileCreationDate.h ├── ruleBase.h ├── ruleExec.h ├── ruleExtension.h ├── ruleInteger.h ├── ruleDate.cpp ├── ruleReplace.cpp ├── ruleFilename.cpp ├── ruleFilesize.h ├── ruleDir.cpp ├── ruleExtension.cpp ├── ruleInteger.cpp ├── ruleFileCreationDate.cpp ├── ruleExec.cpp └── ruleFilesize.cpp ├── version.h.in ├── Tests ├── tests.h └── tests.cpp ├── cfgvarsingleton.cpp ├── Progressator ├── progressator.h └── progressator.cpp ├── cfgvarsingleton.h ├── AnyOption ├── LICENSE ├── anyoption.h └── anyoption.cpp ├── renamer.h ├── main.cpp ├── configurationparser.h ├── CMakeLists.txt ├── CHANGELOG ├── renamer.cpp ├── README ├── configurationparser.cpp └── LICENSE /Rules/ruleBase.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "ruleBase.h" 4 | 5 | 6 | -------------------------------------------------------------------------------- /version.h.in: -------------------------------------------------------------------------------- 1 | // the configured options and settings for Tutorial 2 | #define VERSION_MAJOR @nomenus-rex_VERSION_MAJOR@ 3 | #define VERSION_MINOR @nomenus-rex_VERSION_MINOR@ 4 | #define VERSION_PATCH @nomenus-rex_VERSION_PATCH@ 5 | -------------------------------------------------------------------------------- /Rules/ruleText.cpp: -------------------------------------------------------------------------------- 1 | #include "ruleText.h" 2 | 3 | RuleText::RuleText(const std::string& _text) 4 | : text {_text} 5 | { 6 | 7 | } 8 | 9 | std::string RuleText::process(const RuleParams&) 10 | { 11 | return text; 12 | } 13 | 14 | -------------------------------------------------------------------------------- /Rules/ruleText.h: -------------------------------------------------------------------------------- 1 | #ifndef RULETEXT_H 2 | #define RULETEXT_H 3 | 4 | #include "ruleBase.h" 5 | 6 | class RuleText: public RuleBase 7 | { 8 | public: 9 | explicit RuleText(const std::string& text); 10 | std::string process(const RuleParams&) override; 11 | private: 12 | std::string text; 13 | }; 14 | 15 | #endif 16 | -------------------------------------------------------------------------------- /Tests/tests.h: -------------------------------------------------------------------------------- 1 | #ifndef TESTS_H 2 | #define TESTS_H 3 | #include 4 | 5 | #include "../Rules/rules.h" 6 | //#include "../Progressator/progressator.h" 7 | 8 | enum class WhatToInit {relative, absolute, in_process}; 9 | enum class WhatToTest {getString, in_process}; 10 | 11 | void tests(); 12 | 13 | 14 | #endif 15 | -------------------------------------------------------------------------------- /Rules/ruleDate.h: -------------------------------------------------------------------------------- 1 | #ifndef RULEDATE_H 2 | #define RULEDATE_H 3 | 4 | #include "ruleBase.h" 5 | #include 6 | 7 | class RuleDate: public RuleBase 8 | { 9 | public: 10 | explicit RuleDate(const std::string& format); 11 | std::string process(const RuleParams&) override; 12 | private: 13 | std::string result; 14 | }; 15 | 16 | #endif 17 | -------------------------------------------------------------------------------- /Rules/ruleReplace.h: -------------------------------------------------------------------------------- 1 | #ifndef RULEREPLACE_H 2 | #define RULEREPLACE_H 3 | 4 | #include "ruleBase.h" 5 | 6 | class RuleReplace: public RuleBase 7 | { 8 | public: 9 | RuleReplace(const std::string& _what, const std::string& _to); 10 | std::string process(const RuleParams&) override; 11 | private: 12 | std::string what; 13 | std::string to; 14 | }; 15 | 16 | #endif 17 | -------------------------------------------------------------------------------- /Rules/rules.h: -------------------------------------------------------------------------------- 1 | #ifndef RULES_H 2 | #define RULES_H 3 | 4 | #include "ruleText.h" 5 | #include "ruleInteger.h" 6 | #include "ruleExtension.h" 7 | #include "ruleDir.h" 8 | #include "ruleFilename.h" 9 | #include "ruleFilesize.h" 10 | #include "ruleFileCreationDate.h" 11 | #include "ruleReplace.h" 12 | #include "ruleExec.h" 13 | #include "ruleDate.h" 14 | 15 | #endif // RULES_H 16 | -------------------------------------------------------------------------------- /Rules/ruleFilename.h: -------------------------------------------------------------------------------- 1 | #ifndef RULEFILENAME_H 2 | #define RULEFILENAME_H 3 | 4 | #include "ruleBase.h" 5 | #include 6 | 7 | class RuleFilename: public RuleBase 8 | { 9 | public: 10 | enum class Mode {lowercase, uppercase, sic}; 11 | explicit RuleFilename(Mode _mode); 12 | std::string process(const RuleParams&) override; 13 | private: 14 | Mode mode; 15 | }; 16 | 17 | #endif 18 | -------------------------------------------------------------------------------- /Rules/ruleDir.h: -------------------------------------------------------------------------------- 1 | #ifndef RULEDIR_H 2 | #define RULEDIR_H 3 | 4 | #include "ruleBase.h" 5 | #include 6 | 7 | class RuleDir: public RuleBase 8 | { 9 | public: 10 | enum class Mode {whole, parent_only}; 11 | RuleDir(Mode _mode, const std::string& _separator); 12 | std::string process(const RuleParams&) override; 13 | private: 14 | Mode mode; 15 | std::string separator; 16 | }; 17 | 18 | #endif 19 | -------------------------------------------------------------------------------- /Rules/ruleFileCreationDate.h: -------------------------------------------------------------------------------- 1 | #ifndef RULEFILECREATIONDATE_H 2 | #define RULEFILECREATIONDATE_H 3 | 4 | #include "ruleBase.h" 5 | #include 6 | 7 | class RuleFileCreationDate: public RuleBase 8 | { 9 | public: 10 | explicit RuleFileCreationDate(const std::string& format); 11 | std::string process(const RuleParams&) override; 12 | private: 13 | std::string format; 14 | 15 | }; 16 | 17 | #endif 18 | -------------------------------------------------------------------------------- /Rules/ruleBase.h: -------------------------------------------------------------------------------- 1 | #ifndef RULEBASE_H 2 | #define RULEBASE_H 3 | 4 | #include 5 | #include 6 | 7 | struct RuleParams 8 | { 9 | std::filesystem::path& absolute_path; 10 | std::filesystem::path& relative_path; 11 | std::string& name_in_process; 12 | }; 13 | 14 | class RuleBase 15 | { 16 | public: 17 | virtual std::string process(const RuleParams&) = 0; 18 | }; 19 | 20 | #endif // RULE_H 21 | -------------------------------------------------------------------------------- /Rules/ruleExec.h: -------------------------------------------------------------------------------- 1 | #ifndef RULEEXEC_H 2 | #define RULEEXEC_H 3 | 4 | #include "ruleBase.h" 5 | #include 6 | 7 | class RuleExec: public RuleBase 8 | { 9 | public: 10 | RuleExec(const std::string& command, const std::string& placeholder); 11 | std::string process(const RuleParams&) override; 12 | private: 13 | std::string command; 14 | std::string placeholder; 15 | 16 | }; 17 | 18 | #endif 19 | 20 | -------------------------------------------------------------------------------- /cfgvarsingleton.cpp: -------------------------------------------------------------------------------- 1 | #include "cfgvarsingleton.h" 2 | 3 | CfgVarSingleton::CfgVarSingleton() 4 | : nomenus_ver_str { std::to_string(VERSION_MAJOR)+"." 5 | +std::to_string(VERSION_MINOR)+"." 6 | +std::to_string(VERSION_PATCH) 7 | } 8 | , ask_confirmation_for_file_processing {true} 9 | , verbose {true} 10 | , amount_of_bijections_printed {10} 11 | { 12 | 13 | } 14 | 15 | vstream vcout; 16 | 17 | 18 | -------------------------------------------------------------------------------- /Rules/ruleExtension.h: -------------------------------------------------------------------------------- 1 | #ifndef RULEEXTENSION_H 2 | #define RULEEXTENSION_H 3 | 4 | #include "ruleBase.h" 5 | #include 6 | 7 | class RuleExtension: public RuleBase 8 | { 9 | public: 10 | enum class Mode {lowercase, uppercase, sic}; 11 | RuleExtension(Mode _mode, const std::string& _ext); 12 | std::string process(const RuleParams&) override; 13 | private: 14 | Mode mode; 15 | std::string ext; 16 | }; 17 | 18 | #endif 19 | -------------------------------------------------------------------------------- /Progressator/progressator.h: -------------------------------------------------------------------------------- 1 | #ifndef PROGRESSATOR_H 2 | #define PROGRESSATOR_H 3 | 4 | #include 5 | 6 | class Progressator 7 | { 8 | public: 9 | Progressator(int total); 10 | void setTotal(int total); 11 | void inc(int delta = 1); 12 | void print(); 13 | void test(); 14 | 15 | private: 16 | void count_decimal_digits_in_total(); 17 | 18 | int total; 19 | int decimal_digits_in_total; 20 | int current; 21 | 22 | uint64_t time_previous; 23 | uint64_t time_per_inc; 24 | 25 | }; 26 | #endif 27 | -------------------------------------------------------------------------------- /Rules/ruleInteger.h: -------------------------------------------------------------------------------- 1 | #ifndef RULEINTEGER_H 2 | #define RULEINTEGER_H 3 | 4 | #include "ruleBase.h" 5 | #include 6 | #include 7 | 8 | class RuleInteger: public RuleBase 9 | { 10 | public: 11 | enum class Mode {global, local_at_every_dir}; 12 | 13 | RuleInteger(Mode _mode, int _start, int _step, int _padding); 14 | std::string process(const RuleParams&) override; 15 | private: 16 | int number; 17 | std::map number_per_path; 18 | int step; 19 | Mode mode; 20 | int zero_padding_size; 21 | }; 22 | 23 | #endif 24 | -------------------------------------------------------------------------------- /Rules/ruleDate.cpp: -------------------------------------------------------------------------------- 1 | #include "ruleDate.h" 2 | #include 3 | 4 | RuleDate::RuleDate(const std::string& format) 5 | { 6 | const size_t buffer_size = 80; 7 | time_t rawtime; 8 | struct tm * timeinfo; 9 | char buffer [buffer_size]; 10 | 11 | time (&rawtime); 12 | timeinfo = localtime (&rawtime); 13 | 14 | size_t res = strftime (buffer, buffer_size, format.c_str(), timeinfo); 15 | if (res == 0) 16 | { 17 | std::cerr<< "Result string for date is too long and exceeds the size of the buffer("< 3 | #include 4 | 5 | RuleFilename::RuleFilename(Mode _mode) 6 | : mode{_mode} 7 | { 8 | 9 | } 10 | 11 | std::string RuleFilename::process(const RuleParams& params) 12 | { 13 | std::string result = params.relative_path.stem(); 14 | 15 | switch (mode) 16 | { 17 | case Mode::lowercase: 18 | { 19 | icu::UnicodeString icu_str(result.c_str()); 20 | result.clear(); 21 | icu_str.toLower(); 22 | icu_str.toUTF8String(result); 23 | }break; 24 | case Mode::uppercase: 25 | { 26 | icu::UnicodeString icu_str(result.c_str()); 27 | result.clear(); 28 | icu_str.toUpper(); 29 | icu_str.toUTF8String(result); 30 | }break; 31 | case Mode::sic: 32 | { 33 | 34 | }break; 35 | } 36 | 37 | return result; 38 | } 39 | 40 | -------------------------------------------------------------------------------- /Rules/ruleFilesize.h: -------------------------------------------------------------------------------- 1 | #ifndef RULEFILESIZE_H 2 | #define RULEFILESIZE_H 3 | 4 | #include "ruleBase.h" 5 | #include 6 | #include 7 | 8 | constexpr std::size_t operator""_KiB(unsigned long long int x) {return 1024ULL * x;} 9 | constexpr std::size_t operator""_MiB(unsigned long long int x) {return 1024_KiB * x;} 10 | constexpr std::size_t operator""_GiB(unsigned long long int x) {return 1024_MiB * x;} 11 | 12 | class RuleFilesize: public RuleBase 13 | { 14 | public: 15 | enum class Dimension {B, KiB, MiB, GiB}; 16 | RuleFilesize(Dimension _dimension, const std::string& _decimal_separator, bool _show_dimension); 17 | std::string process(const RuleParams&) override; 18 | private: 19 | Dimension dimension; 20 | std::string decimal_separator; 21 | bool show_dimension; 22 | struct iB2size{std::string name; uintmax_t size;}; 23 | std::map dimension_data; 24 | }; 25 | 26 | #endif 27 | -------------------------------------------------------------------------------- /Rules/ruleDir.cpp: -------------------------------------------------------------------------------- 1 | #include "ruleDir.h" 2 | 3 | #include 4 | 5 | RuleDir::RuleDir(Mode _mode, const std::string& _separator) 6 | : mode {_mode} 7 | , separator {_separator} 8 | { 9 | 10 | } 11 | 12 | std::string RuleDir::process(const RuleParams& params) 13 | { 14 | std::string result; 15 | std::vector path; 16 | for (auto it = params.relative_path.begin(); it != params.relative_path.end(); ++it) 17 | { 18 | path.push_back(*it); 19 | } 20 | 21 | path.pop_back(); // remove filename. We need only dir names. 22 | 23 | if (mode == Mode::parent_only && path.size() >= 1) 24 | { 25 | result = path[path.size()-1]; 26 | }else 27 | if (mode == Mode::whole && path.size() > 0) 28 | { 29 | for (const auto& dir: path) 30 | { 31 | result += dir + separator; 32 | } 33 | 34 | // Removing the separator from the end of the string 35 | result.erase(result.size() - separator.size()); 36 | } 37 | 38 | return result; 39 | } 40 | 41 | -------------------------------------------------------------------------------- /Rules/ruleExtension.cpp: -------------------------------------------------------------------------------- 1 | #include "ruleExtension.h" 2 | #include 3 | #include 4 | 5 | RuleExtension::RuleExtension(Mode _mode, const std::string& _ext) 6 | : mode{_mode} 7 | , ext {_ext} 8 | { 9 | 10 | } 11 | 12 | std::string RuleExtension::process(const RuleParams& params) 13 | { 14 | std::string result; 15 | 16 | if (ext == "") 17 | { 18 | result = params.relative_path.extension(); 19 | }else 20 | { 21 | result = ext; 22 | } 23 | 24 | switch (mode) 25 | { 26 | case Mode::lowercase: 27 | { 28 | icu::UnicodeString icu_str(result.c_str()); 29 | result.clear(); 30 | icu_str.toLower(); 31 | icu_str.toUTF8String(result); 32 | }break; 33 | case Mode::uppercase: 34 | { 35 | icu::UnicodeString icu_str(result.c_str()); 36 | result.clear(); 37 | icu_str.toUpper(); 38 | icu_str.toUTF8String(result); 39 | }break; 40 | case Mode::sic: 41 | { 42 | 43 | }break; 44 | } 45 | 46 | return result; 47 | } 48 | 49 | -------------------------------------------------------------------------------- /Rules/ruleInteger.cpp: -------------------------------------------------------------------------------- 1 | #include "ruleInteger.h" 2 | #include 3 | 4 | RuleInteger::RuleInteger(Mode _mode, int _start, int _step, int _padding) 5 | : number {_start} 6 | , step {_step} 7 | , mode {_mode} 8 | , zero_padding_size {_padding} 9 | { 10 | 11 | } 12 | 13 | std::string RuleInteger::process(const RuleParams& params) 14 | { 15 | std::string result; 16 | switch (mode) 17 | { 18 | case Mode::global: 19 | { 20 | result = std::to_string(number); 21 | result.insert(0, std::max(0, zero_padding_size - static_cast(result.size())), '0'); 22 | number++; 23 | }break; 24 | case Mode::local_at_every_dir: 25 | { 26 | std::filesystem::path path = params.relative_path; 27 | path.remove_filename(); 28 | result = std::to_string(number_per_path[path]); 29 | result.insert(0, std::max(0, zero_padding_size - static_cast(result.size())), '0'); 30 | number_per_path[path]++; 31 | } 32 | } 33 | 34 | return result; 35 | } 36 | 37 | 38 | -------------------------------------------------------------------------------- /cfgvarsingleton.h: -------------------------------------------------------------------------------- 1 | #ifndef CFGVARSINGLETON_H 2 | #define CFGVARSINGLETON_H 3 | 4 | #include 5 | #include 6 | #include "version.h" 7 | 8 | class CfgVarSingleton 9 | { 10 | public: 11 | static CfgVarSingleton& Instance() 12 | { 13 | static CfgVarSingleton theSingleInstance; 14 | return theSingleInstance; 15 | } 16 | 17 | const std::string nomenus_ver_str; 18 | bool ask_confirmation_for_file_processing; 19 | bool verbose; 20 | int amount_of_bijections_printed; 21 | 22 | private: 23 | CfgVarSingleton(); 24 | CfgVarSingleton(const CfgVarSingleton& root) = delete; 25 | CfgVarSingleton& operator=(const CfgVarSingleton&) = delete; 26 | }; 27 | 28 | 29 | class vstream: public std::ostream 30 | { 31 | 32 | 33 | }; 34 | 35 | template 36 | vstream& operator<<(vstream& out, T str) 37 | { 38 | if (CfgVarSingleton::Instance().verbose) 39 | { 40 | std::cout << str; 41 | } 42 | 43 | return out; 44 | } 45 | 46 | extern vstream vcout; 47 | 48 | #endif 49 | -------------------------------------------------------------------------------- /Rules/ruleFileCreationDate.cpp: -------------------------------------------------------------------------------- 1 | #include "ruleFileCreationDate.h" 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | 10 | RuleFileCreationDate::RuleFileCreationDate(const std::string& _format) 11 | : format{_format} 12 | { 13 | 14 | } 15 | 16 | std::string RuleFileCreationDate::process(const RuleParams& params) 17 | { 18 | //std::string result; 19 | struct stat st; 20 | const size_t buffer_size = 80; 21 | char buffer [buffer_size]; 22 | 23 | stat(params.absolute_path.c_str(), &st); 24 | time_t rawtime = st.st_mtim.tv_sec; 25 | 26 | struct tm* timeinfo = localtime (&rawtime); 27 | 28 | size_t res = strftime (buffer, buffer_size, format.c_str(), timeinfo); 29 | if (res == 0) 30 | { 31 | std::cerr<< "Result string for date is too long and exceeds the size of the buffer("< 5 | #include 6 | #include 7 | #include 8 | 9 | #include "Rules/rules.h" 10 | 11 | namespace fs = std::filesystem; 12 | 13 | class Renamer 14 | { 15 | public: 16 | enum class CopyOrRename{copy, rename}; 17 | enum class SortMode{sic, az, za}; 18 | Renamer(); 19 | //////////////////// 20 | 21 | //fs::path applyRulesToOneFilename(const RuleParams& params); 22 | void createRenameBijection(); 23 | void testRenameBijection() const; 24 | void executeRenameBijection(); 25 | void printRenameBijection() const; 26 | 27 | fs::path source_dir; 28 | fs::path destination_dir; 29 | bool keep_dir_structure; 30 | CopyOrRename copy_or_rename; 31 | SortMode sort_mode; 32 | std::vector> rules; 33 | 34 | 35 | private: 36 | 37 | std::vector> rename_vector; 38 | 39 | void getSourceFilenames(std::vector>& rename_vector, const fs::path& source_dir); 40 | void sortSourceFilenames(std::vector>& rename_vector, SortMode sort_mode); 41 | }; 42 | 43 | #endif // RENAMER_H 44 | -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "renamer.h" 5 | #include "configurationparser.h" 6 | #include "cfgvarsingleton.h" 7 | #include "Tests/tests.h" 8 | 9 | int main(int argc, char *argv[]) 10 | { 11 | #if !defined(NDEBUG) 12 | tests(); 13 | #endif 14 | 15 | Renamer renamer; 16 | // ConfigurationParser also fills CfgVarSingleton 17 | ConfigurationParser cfg_parser(argc, argv, renamer); 18 | 19 | vcout << "Nomenus-rex(" << CfgVarSingleton::Instance().nomenus_ver_str <<")\n"; 20 | 21 | renamer.createRenameBijection(); 22 | renamer.testRenameBijection(); 23 | renamer.printRenameBijection(); 24 | 25 | 26 | if (CfgVarSingleton::Instance().ask_confirmation_for_file_processing) 27 | { 28 | //v1cout new_cout; 29 | std::cerr << "Press 'y' to process the files. Other button to cancel." << std::endl; 30 | char approvement; 31 | std::cin >> approvement; 32 | if (approvement == 'y') 33 | { 34 | renamer.executeRenameBijection(); 35 | vcout << "The process is done." << std::endl; 36 | }else 37 | { 38 | vcout << "The process is canceled." << std::endl; 39 | } 40 | }else 41 | { 42 | renamer.executeRenameBijection(); 43 | } 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /Rules/ruleExec.cpp: -------------------------------------------------------------------------------- 1 | #include "ruleExec.h" 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | 9 | RuleExec::RuleExec(const std::string& _command, const std::string& _placeholder) 10 | : command{_command} 11 | , placeholder{_placeholder} 12 | { 13 | 14 | } 15 | 16 | std::string RuleExec::process(const RuleParams& params) 17 | { 18 | std::string result; 19 | 20 | /// CMD GENERATION ///////// 21 | std::string finished_command = command; 22 | size_t pos = 0; 23 | while((pos = finished_command.find(placeholder, pos)) != std::string::npos) 24 | { 25 | finished_command.replace(pos, placeholder.length(), params.absolute_path); 26 | pos += placeholder.length(); 27 | } 28 | //command = "echo '' | grep -Eo '[0-9]+'"; 29 | /// CMD EXECUTION ////////// 30 | 31 | 32 | std::array buffer; 33 | std::unique_ptr pipe(popen(finished_command.c_str(), "r"), pclose); 34 | if (!pipe) 35 | { 36 | throw std::runtime_error("popen() failed!"); 37 | } 38 | while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) 39 | { 40 | result += buffer.data(); 41 | } 42 | 43 | if (result.size() > 0 && result[result.size()-1] == '\n') 44 | { 45 | result.pop_back(); 46 | } 47 | 48 | return result; 49 | } 50 | -------------------------------------------------------------------------------- /Rules/ruleFilesize.cpp: -------------------------------------------------------------------------------- 1 | #include "ruleFilesize.h" 2 | #include 3 | #include 4 | #include 5 | 6 | RuleFilesize::RuleFilesize(Dimension _dimension, const std::string& _decimal_separator, bool _show_dimension) 7 | : dimension{_dimension} 8 | , decimal_separator {_decimal_separator} 9 | , show_dimension {_show_dimension} 10 | , dimension_data { {Dimension::B, {.name = "B", .size = 1}}, 11 | {Dimension::KiB, {.name = "KiB", .size = 1_KiB}}, 12 | {Dimension::MiB, {.name = "MiB", .size = 1_MiB}}, 13 | {Dimension::GiB, {.name = "GiB", .size = 1_GiB}} 14 | } 15 | { 16 | 17 | } 18 | 19 | std::string RuleFilesize::process(const RuleParams& params) 20 | { 21 | std::string result; 22 | 23 | uintmax_t fsize = std::filesystem::file_size(params.absolute_path); 24 | double dimensioned_size = (1.0*fsize) / (1.0*dimension_data[dimension].size); 25 | 26 | double pre_dot; 27 | double post_dot = std::modf(dimensioned_size, &pre_dot); 28 | int int_pre_dot = pre_dot; 29 | 30 | std::string str_post_dot = std::to_string(post_dot); 31 | 32 | 33 | result += std::to_string(int_pre_dot); 34 | result += decimal_separator; 35 | result += str_post_dot.substr(2, 3); 36 | if (show_dimension) 37 | { 38 | result += dimension_data[dimension].name; 39 | } 40 | 41 | return result; 42 | 43 | } 44 | -------------------------------------------------------------------------------- /configurationparser.h: -------------------------------------------------------------------------------- 1 | #ifndef CONFIGURATIONPARSER_H 2 | #define CONFIGURATIONPARSER_H 3 | 4 | #include 5 | #include 6 | #include "renamer.h" 7 | #include 8 | 9 | using namespace libconfig; 10 | 11 | class ConfigurationParser 12 | { 13 | public: 14 | ConfigurationParser(int argc, char *argv[], Renamer& renamer); 15 | void printTypicalConfig(); 16 | 17 | private: 18 | template 19 | void getRuleVar(const Setting &rule, 20 | const std::string& var_name, 21 | const std::string& rule_name, 22 | T& var) 23 | { 24 | bool var_present = rule.lookupValue(var_name, var); 25 | if (!var_present) 26 | { 27 | std::cerr << "\nERROR: There is no '" << var_name << "' variable in the '" << rule_name <<"' rule." << std::endl; 28 | exit(EXIT_FAILURE); 29 | } 30 | } 31 | 32 | template 33 | void getVar(const Setting &rule, 34 | const std::string& var_name, 35 | T& var) 36 | { 37 | bool var_present = rule.lookupValue(var_name, var); 38 | if (!var_present) 39 | { 40 | std::cerr << "\nERROR: There is no '" << var_name << "' variable" << std::endl; 41 | exit(EXIT_FAILURE); 42 | } 43 | } 44 | 45 | template 46 | T enumParser(const Setting &settings, 47 | const std::string& rule_type, 48 | const std::string& var_name, 49 | const std::initializer_list>& init_list 50 | ) 51 | { 52 | std::string str_mode; 53 | getRuleVar(settings, var_name, rule_type, str_mode); 54 | 55 | std::map str2enum = std::move(init_list); 56 | 57 | if (str2enum.find(str_mode) != str2enum.end()) 58 | { 59 | T res = str2enum.at(str_mode); 60 | return res; 61 | } 62 | 63 | std::cerr << "\nERROR: Unknown value '" << str_mode << "' " << 64 | " of the variable '" << var_name << "' " << 65 | " in the rule '" << rule_type << "' \n"; 66 | exit(EXIT_FAILURE); 67 | } 68 | 69 | void makeSureThatConfigDirIsExist(); 70 | std::string getConfigPathString(std::string raw_parameter); 71 | }; 72 | 73 | #endif // CONFIGURATIONPARSER_H 74 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.5) 2 | 3 | project(nomenus-rex 4 | VERSION 0.8.1 5 | HOMEPAGE_URL "https://github.com/ANGulchenko/nomenus-rex" 6 | DESCRIPTION "Nomenus-rex is a CLI utility for the file mass-renaming.") 7 | 8 | configure_file(version.h.in version.h) 9 | 10 | set(CMAKE_CXX_FLAGS "-Wall -Wextra") 11 | set(CMAKE_CXX_STANDARD 17) 12 | set(CMAKE_CXX_STANDARD_REQUIRED ON) 13 | 14 | add_custom_target(Docs SOURCES 15 | CHANGELOG 16 | README 17 | ) 18 | 19 | ADD_LIBRARY(AnyOption STATIC 20 | AnyOption/anyoption.cpp AnyOption/anyoption.h 21 | ) 22 | 23 | ADD_LIBRARY(Progressator STATIC 24 | Progressator/progressator.cpp Progressator/progressator.h 25 | ) 26 | 27 | ADD_LIBRARY(Rules STATIC 28 | Rules/rules.h 29 | Rules/ruleBase.cpp Rules/ruleBase.h 30 | Rules/ruleDate.cpp Rules/ruleDate.h 31 | Rules/ruleText.cpp Rules/ruleText.h 32 | Rules/ruleInteger.cpp Rules/ruleInteger.h 33 | Rules/ruleExtension.cpp Rules/ruleExtension.h 34 | Rules/ruleDir.cpp Rules/ruleDir.h 35 | Rules/ruleFilename.cpp Rules/ruleFilename.h 36 | Rules/ruleFilesize.cpp Rules/ruleFilesize.h 37 | Rules/ruleFileCreationDate.cpp Rules/ruleFileCreationDate.h 38 | Rules/ruleReplace.cpp Rules/ruleReplace.h 39 | Rules/ruleExec.cpp Rules/ruleExec.h 40 | ) 41 | 42 | ADD_LIBRARY(Tests STATIC 43 | Tests/tests.cpp Tests/tests.h 44 | ) 45 | 46 | add_executable (nomenus-rex 47 | main.cpp 48 | configurationparser.cpp configurationparser.h 49 | renamer.cpp renamer.h 50 | cfgvarsingleton.cpp cfgvarsingleton.h 51 | ) 52 | 53 | find_package(ICU REQUIRED COMPONENTS data i18n uc dt) 54 | 55 | target_link_libraries(nomenus-rex AnyOption Tests Rules Progressator config++) 56 | target_link_libraries(nomenus-rex ICU::data ICU::i18n ICU::uc ICU::dt) 57 | 58 | target_include_directories(nomenus-rex PUBLIC 59 | "${PROJECT_BINARY_DIR}" 60 | "${PROJECT_SOURCE_DIR}" 61 | ) 62 | 63 | 64 | -------------------------------------------------------------------------------- /Progressator/progressator.cpp: -------------------------------------------------------------------------------- 1 | #include "progressator.h" 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | 8 | Progressator::Progressator(int _total) 9 | : total {_total} 10 | , decimal_digits_in_total {0} 11 | , current {0} 12 | , time_previous {0} 13 | , time_per_inc {0} 14 | { 15 | count_decimal_digits_in_total(); 16 | } 17 | 18 | void Progressator::setTotal(int _total) 19 | { 20 | total = _total; 21 | count_decimal_digits_in_total(); 22 | } 23 | 24 | void Progressator::count_decimal_digits_in_total() 25 | { 26 | decimal_digits_in_total = 0; 27 | int num = total; 28 | while (num != 0) 29 | { 30 | decimal_digits_in_total++; 31 | num /= 10; 32 | } 33 | } 34 | 35 | void Progressator::inc(int _delta) 36 | { 37 | uint64_t ms = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); 38 | if (time_previous == 0) 39 | { 40 | time_previous = ms; 41 | } 42 | time_per_inc = (ms - time_previous) / 2; 43 | time_previous = ms; 44 | 45 | current += _delta; 46 | } 47 | 48 | void Progressator::print() 49 | { 50 | int percent = 100 * current / total; 51 | std::string percent_str_tiles(percent / 5, '='); 52 | std::string percent_str_postfix(20 - percent_str_tiles.size(), ' '); 53 | std::string percent_str_back = percent_str_tiles + percent_str_postfix; 54 | std::string percentage = std::to_string(percent)+"%"; 55 | percent_str_back.replace((percent_str_back.size() - percentage.size())/2, percentage.size(), percentage); 56 | std::string percent_str = "["+percent_str_back+"]"; 57 | 58 | std::cout << '\r' 59 | <<"[" << std::setfill('0') << std::setw(decimal_digits_in_total) << current << "/" << total << "] " 60 | << percent_str 61 | << " ETC:"<< std::setfill('0') << std::setw(6) << time_per_inc * (total - current) << " msec."; 62 | std::flush(std::cout); 63 | } 64 | 65 | /*void Progressator::test() 66 | { 67 | Progressator progressator(1000); 68 | for (int i = 0; i < 1000; i++) 69 | { 70 | progressator.inc(); 71 | progressator.print(); 72 | std::this_thread::sleep_for(std::chrono::milliseconds(10)); 73 | } 74 | std::cout << std::endl; 75 | }*/ 76 | -------------------------------------------------------------------------------- /CHANGELOG: -------------------------------------------------------------------------------- 1 | ─────────────────┨ 0.8.1 ┠───────────────── 2 | 1) -l parameter to suppress the text info from printing (file processing 3 | confirmation and error will be printed anyway) 4 | 5 | 2) -p parameter limits the amount of bijections printed. 6 | 7 | 3) Added some debug/processing info (files amount and amount of time spent) 8 | 9 | 4) Small refactoring here and there. 10 | 11 | ─────────────────┨ 0.8.0 ┠───────────────── 12 | 1) New rule: "exec" allows to run any arbitrary command and use its stdout 13 | output in the new filename. 14 | 15 | 2) In case of the error during the file renaming, the program will try to revert 16 | changes. 17 | 18 | ─────────────────┨ 0.7.0 ┠───────────────── 19 | 1) New rule: File creation time. The syntax is the same as in the Date rule. 20 | 21 | 2) Removed an annoying "boilerplate" code. 22 | 23 | ─────────────────┨ 0.6.2 ┠───────────────── 24 | 1) Significant improvement (~1000 times faster) of the collision test. 25 | This test checks for identical result filenames. While moving 26 | identical names will cause data loss. Test run with ~21k filenames 27 | decreased its runtime from ~18 seconds to ~20k microseconds! 28 | 29 | ─────────────────┨ 0.6.1 ┠───────────────── 30 | 1) Fixed bug in RuleDir for a top level files. 31 | 32 | ─────────────────┨ 0.6.0 ┠───────────────── 33 | 1) New CLI parameter e/example for printing out default config 34 | with autofilled source/destination fields according to the current 35 | directory. 36 | 37 | ─────────────────┨ 0.5.3 ┠───────────────── 38 | 1) Few 'const' and unique_ptr here and there. 39 | 40 | 2) A tiny aesthetical tuning of printing out the filename pairs. 41 | 42 | ─────────────────┨ 0.5.2 ┠───────────────── 43 | 1) New parameter for disabling file processing confirmation. 44 | May be useful for scripts. 45 | 46 | 2) Nice progress bar 47 | 48 | ─────────────────┨ 0.5.1 ┠───────────────── 49 | 1) Added different modes of file sorting (Unicode-friendly) 50 | 51 | 2) Small refactoring plus checking if the source dir exists. 52 | 53 | ─────────────────┨ 0.5.0 ┠───────────────── 54 | 1) Most rules are covered with tests now. 55 | 56 | 2) ICU library is used now for uppercase/lowercase text transforms 57 | 58 | ─────────────────┨ 0.4.0 ┠───────────────── 59 | 1) Some template magic in the configuration parser. It should make adding 60 | new rules easier and less error-prone. 61 | 62 | 2) New "rule": replace. Search and replace all occurrences of the 63 | substring to the new string in the CURRENT UNFINISHED FILENAME. It is 64 | a new type of rules. 65 | 66 | 3) Now files are alphabetically sorted before processing. 67 | 68 | 4) Tests. Nothing for users, but I expect a slightly less amount of errors 69 | in the code. 70 | 71 | 5) Documentation now is more... better. 72 | 73 | ─────────────────┨ 0.3.0 ┠───────────────── 74 | New "rule": filename. Just an original filename without an extension. 75 | New "rule": filesize. 76 | Readme fix: text->ext typo. 77 | -------------------------------------------------------------------------------- /Tests/tests.cpp: -------------------------------------------------------------------------------- 1 | #include "tests.h" 2 | 3 | void testRule(WhatToInit whatInit, 4 | WhatToTest whatTest, 5 | RuleBase& rule, 6 | const std::string& init_string, 7 | const std::string& correct_answer); 8 | 9 | 10 | void tests() 11 | { 12 | /// RuleExec ////////////////////////////////////////////////////////////////// 13 | { 14 | RuleExec rule("echo '' | grep -Eo '[0-9]+'", ""); 15 | testRule(WhatToInit::absolute, WhatToTest::getString, rule, "/test/ololo0001.txt", "0001"); 16 | } 17 | /// RuleText ////////////////////////////////////////////////////////////////// 18 | { 19 | RuleText rule("Test"); 20 | testRule(WhatToInit::relative, WhatToTest::getString, rule, "", "Test"); 21 | } 22 | { 23 | RuleText rule(""); 24 | testRule(WhatToInit::relative, WhatToTest::getString, rule, "", ""); 25 | } 26 | 27 | /// RuleDir ////////////////////////////////////////////////////////////////// 28 | 29 | { 30 | RuleDir rule(RuleDir::Mode::whole, "_"); 31 | testRule(WhatToInit::relative, WhatToTest::getString, rule, 32 | "dir/subdir1/subdir2/file.dat", 33 | "dir_subdir1_subdir2"); 34 | } 35 | { 36 | RuleDir rule(RuleDir::Mode::whole, ""); 37 | testRule(WhatToInit::relative, WhatToTest::getString, rule, 38 | "dir/subdir1/subdir2/file.dat", 39 | "dirsubdir1subdir2"); 40 | } 41 | 42 | { 43 | RuleDir rule(RuleDir::Mode::whole, ""); 44 | testRule(WhatToInit::relative, WhatToTest::getString, rule, 45 | "file.dat", 46 | ""); 47 | } 48 | { 49 | RuleDir rule(RuleDir::Mode::parent_only, "_"); 50 | testRule(WhatToInit::relative, WhatToTest::getString, rule, 51 | "dir/subdir1/subdir2/file.dat", 52 | "subdir2"); 53 | } 54 | { 55 | RuleDir rule(RuleDir::Mode::whole, "_"); 56 | testRule(WhatToInit::relative, WhatToTest::getString, rule, 57 | "dir/поддиректория/الدليل/file.dat", 58 | "dir_поддиректория_الدليل"); 59 | } 60 | { 61 | RuleDir rule(RuleDir::Mode::whole, "[separator]"); 62 | testRule(WhatToInit::relative, WhatToTest::getString, rule, 63 | "dir/subdir1/subdir2/file.dat", 64 | "dir[separator]subdir1[separator]subdir2"); 65 | } 66 | 67 | /// RuleExtension ////////////////////////////////////////////////////////////////// 68 | { 69 | RuleExtension rule(RuleExtension::Mode::lowercase, ""); 70 | testRule(WhatToInit::relative, WhatToTest::getString, rule, 71 | "dir/subdir1/subdir2/file.dAt", 72 | ".dat"); 73 | } 74 | 75 | { 76 | RuleExtension rule(RuleExtension::Mode::lowercase, ""); 77 | testRule(WhatToInit::relative, WhatToTest::getString, rule, 78 | "dir/subdir1/subdir2/file.РаСширение", 79 | ".расширение"); 80 | } 81 | 82 | { 83 | RuleExtension rule(RuleExtension::Mode::lowercase, ""); 84 | testRule(WhatToInit::relative, WhatToTest::getString, rule, 85 | "dir/subdir1/subdir2/file.", 86 | "."); 87 | } 88 | 89 | { 90 | RuleExtension rule(RuleExtension::Mode::lowercase, ".ext"); 91 | testRule(WhatToInit::relative, WhatToTest::getString, rule, 92 | "dir/subdir1/subdir2/file.dat", 93 | ".ext"); 94 | } 95 | 96 | /// RuleFilename ////////////////////////////////////////////////////////////////// 97 | 98 | { 99 | RuleFilename rule(RuleFilename::Mode::lowercase); 100 | testRule(WhatToInit::relative, WhatToTest::getString, rule, 101 | "dir/subdir1/subdir2/fIlE.dAt", 102 | "file"); 103 | } 104 | 105 | { 106 | RuleFilename rule(RuleFilename::Mode::uppercase); 107 | testRule(WhatToInit::relative, WhatToTest::getString, rule, 108 | "dir/subdir1/subdir2/fileфайл.dat", 109 | "FILEФАЙЛ"); 110 | } 111 | 112 | /// RuleInteger ////////////////////////////////////////////////////////////////// 113 | 114 | { 115 | RuleInteger rule(RuleInteger::Mode::global, 0, 1, 4); 116 | 117 | testRule(WhatToInit::relative, WhatToTest::getString, rule, 118 | "", 119 | "0000"); 120 | testRule(WhatToInit::relative, WhatToTest::getString, rule, 121 | "", 122 | "0001"); 123 | testRule(WhatToInit::relative, WhatToTest::getString, rule, 124 | "", 125 | "0002"); 126 | } 127 | 128 | /// RuleReplace ////////////////////////////////////////////////////////////////// 129 | 130 | { 131 | RuleReplace rule("Bla", "Fuh"); 132 | testRule(WhatToInit::in_process, WhatToTest::in_process, rule, 133 | "123Bla123Bla", 134 | "123Fuh123Fuh"); 135 | } 136 | 137 | { 138 | RuleReplace rule("Bla", ""); 139 | testRule(WhatToInit::in_process, WhatToTest::in_process, rule, 140 | "123Bla123Bla", 141 | "123123"); 142 | } 143 | 144 | { 145 | RuleReplace rule("", "Fuh"); 146 | testRule(WhatToInit::in_process, WhatToTest::in_process, rule, 147 | "123Bla123Bla", 148 | "123Bla123Bla"); 149 | } 150 | 151 | std::cerr << "All tests are done.\n"; 152 | //exit(0); 153 | } 154 | 155 | 156 | void testRule(WhatToInit whatInit, 157 | WhatToTest whatTest, 158 | RuleBase& rule, 159 | const std::string& init_string, 160 | const std::string& correct_answer) 161 | { 162 | 163 | std::string in_process(""); 164 | std::filesystem::path abs(""); 165 | std::filesystem::path rel(""); 166 | 167 | switch (whatInit) 168 | { 169 | case WhatToInit::relative: 170 | { 171 | rel = std::filesystem::path(init_string); 172 | }break; 173 | case WhatToInit::absolute: 174 | { 175 | abs = std::filesystem::path(init_string); 176 | }break; 177 | case WhatToInit::in_process: 178 | { 179 | in_process = init_string; 180 | }break; 181 | } 182 | 183 | 184 | RuleParams params = {.absolute_path = abs, 185 | .relative_path = rel, 186 | .name_in_process = in_process}; 187 | 188 | std::string process_res = rule.process(params); 189 | 190 | switch (whatTest) 191 | { 192 | case WhatToTest::getString: 193 | { 194 | if (std::string res = process_res; res != correct_answer) 195 | { 196 | std::cerr << "(" << typeid(rule).name() <<"): \n" 197 | <<" process() result == \"" << res << "\" \n" 198 | << " but should be \""<< correct_answer <<"\"" << std::endl; 199 | exit(EXIT_FAILURE); 200 | } 201 | }break; 202 | case WhatToTest::in_process: 203 | { 204 | if (std::string res = params.name_in_process; res != correct_answer) 205 | { 206 | std::cerr << "(" << typeid(rule).name() <<"): \n" 207 | <<" name_in_process == \"" << res << "\" \n" 208 | << " but should be \""<< correct_answer <<"\"" << std::endl; 209 | exit(EXIT_FAILURE); 210 | } 211 | }break; 212 | 213 | default: 214 | break; 215 | } 216 | 217 | } 218 | 219 | -------------------------------------------------------------------------------- /renamer.cpp: -------------------------------------------------------------------------------- 1 | #include "renamer.h" 2 | #include "Progressator/progressator.h" 3 | #include "cfgvarsingleton.h" 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | Renamer::Renamer() 12 | : keep_dir_structure {false} 13 | , copy_or_rename {CopyOrRename::copy} 14 | , sort_mode {SortMode::sic} 15 | { 16 | 17 | } 18 | 19 | /////////////////// 20 | 21 | void Renamer::createRenameBijection() 22 | { 23 | vcout << "Start createRenameBijection()... "; 24 | auto start = std::chrono::high_resolution_clock::now(); 25 | 26 | // Get our directories in the array 27 | getSourceFilenames(rename_vector, source_dir); 28 | sortSourceFilenames(rename_vector, sort_mode); 29 | 30 | 31 | for (auto& pair : rename_vector) 32 | { 33 | const std::filesystem::path& dir_entry = pair.first; 34 | fs::path absolute_file_path_source = dir_entry; 35 | fs::path relative_file_path_source = fs::relative(absolute_file_path_source, source_dir); 36 | std::string name_in_process; 37 | 38 | RuleParams params = {.absolute_path = absolute_file_path_source, 39 | .relative_path = relative_file_path_source, 40 | .name_in_process = name_in_process}; 41 | 42 | for (std::unique_ptr& rule: rules) 43 | { 44 | params.name_in_process += rule->process(params); 45 | } 46 | 47 | fs::path relative_file_path_without_filename = relative_file_path_source; 48 | relative_file_path_without_filename.remove_filename(); 49 | fs::path absolute_file_path_destination = destination_dir; 50 | if (keep_dir_structure) 51 | { 52 | absolute_file_path_destination /= relative_file_path_without_filename; 53 | } 54 | absolute_file_path_destination /= name_in_process; 55 | 56 | pair.second = absolute_file_path_destination; 57 | } 58 | 59 | auto stop = std::chrono::high_resolution_clock::now(); 60 | auto duration = std::chrono::duration_cast(stop - start); 61 | auto time_delta = duration.count(); 62 | 63 | vcout << "Finished in " << std::to_string(time_delta) << " microseconds. " 64 | << "(" << std::to_string(rename_vector.size()) << " filename pairs)\n"; 65 | 66 | } 67 | 68 | void Renamer::testRenameBijection() const 69 | { 70 | vcout << "Start testRenameBijection()... "; 71 | auto start = std::chrono::high_resolution_clock::now(); 72 | 73 | std::map result; 74 | std::set new_names; 75 | 76 | for (auto& pair: rename_vector) 77 | { 78 | if (auto ins_res = new_names.insert(pair.second); ins_res.second == false) 79 | { 80 | // Isertion has failed, so we have a name collision here 81 | result[pair.first] = pair.second; 82 | } 83 | } 84 | 85 | if (result.size() > 0) 86 | { 87 | std::cerr << "ERROR: Filenames collision." << std::endl; 88 | for (const auto& element: result) 89 | { 90 | std::cerr << "┌╼" << element.first << "\n" << 91 | "└╳" << element.second << "\n" << std::endl; 92 | } 93 | exit(EXIT_FAILURE); 94 | } 95 | 96 | auto stop = std::chrono::high_resolution_clock::now(); 97 | auto duration = std::chrono::duration_cast(stop - start); 98 | auto time_delta = duration.count(); 99 | 100 | vcout << "Finished in " << std::to_string(time_delta) << " microseconds.\n"; 101 | } 102 | 103 | void Renamer::executeRenameBijection() 104 | { 105 | Progressator progress(rename_vector.size()); 106 | 107 | switch (copy_or_rename) 108 | { 109 | case CopyOrRename::copy: 110 | { 111 | for (auto& element: rename_vector) 112 | { 113 | fs::path dest_dir = element.second; 114 | dest_dir.remove_filename(); 115 | fs::create_directories(dest_dir); 116 | try 117 | { 118 | fs::copy(element.first, element.second, std::filesystem::copy_options::overwrite_existing); 119 | } 120 | catch(std::filesystem::filesystem_error const& ex) 121 | { 122 | // In this case we should just notify the user and that's it: the user can 123 | // delete the previously copied files by his own. 124 | std::cerr << "\n what(): " << ex.what() << '\n'; 125 | exit(EXIT_FAILURE); 126 | } 127 | 128 | progress.inc();progress.print(); 129 | } 130 | }break; 131 | case CopyOrRename::rename: 132 | { 133 | for (auto& element: rename_vector) 134 | { 135 | fs::path dest_dir = element.second; 136 | dest_dir.remove_filename(); 137 | fs::create_directories(dest_dir); 138 | try 139 | { 140 | fs::rename(element.first, element.second); 141 | } 142 | catch(std::filesystem::filesystem_error const& ex) 143 | { 144 | // We need to rename the processed files back 145 | std::cerr << "\n what(): " << ex.what() << '\n'; 146 | std::cerr << "Renaming files back to their original names...\n"; 147 | 148 | std::pair problematic_pair = {ex.path1(), ex.path2()}; 149 | auto iter_of_problematic_pair = std::find(rename_vector.begin(), 150 | rename_vector.end(), 151 | problematic_pair); 152 | 153 | for (auto i = rename_vector.begin(); i != iter_of_problematic_pair; ++i) 154 | { 155 | fs::rename((*i).second, (*i).first); 156 | } 157 | 158 | exit(EXIT_FAILURE); 159 | } 160 | 161 | progress.inc();progress.print(); 162 | } 163 | }break; 164 | } 165 | 166 | } 167 | 168 | 169 | void Renamer::printRenameBijection() const 170 | { 171 | if (!CfgVarSingleton::Instance().verbose) 172 | { 173 | return; 174 | } 175 | 176 | int amount_to_print = rename_vector.size()-1; 177 | if (CfgVarSingleton::Instance().amount_of_bijections_printed >= 0 178 | && CfgVarSingleton::Instance().amount_of_bijections_printed < amount_to_print) 179 | { 180 | amount_to_print = CfgVarSingleton::Instance().amount_of_bijections_printed; 181 | } 182 | 183 | for (size_t i = rename_vector.size() - amount_to_print; i < rename_vector.size(); ++i) 184 | { 185 | std::cout << "┌╼" << rename_vector[i].first << "\n" << 186 | "└►" << rename_vector[i].second << "\n"; 187 | } 188 | 189 | std::cout << std::endl; 190 | } 191 | 192 | 193 | void Renamer::getSourceFilenames(std::vector>& rename_vector, const fs::path& dir) 194 | { 195 | for (const fs::directory_entry& dir_entry : fs::recursive_directory_iterator(dir)) 196 | { 197 | if (!std::filesystem::is_directory(dir_entry)) 198 | { 199 | rename_vector.push_back(std::pair(dir_entry, "")); 200 | } 201 | } 202 | } 203 | 204 | void Renamer::sortSourceFilenames(std::vector>& rename_vector, SortMode sort_mode) 205 | { 206 | switch (sort_mode) 207 | { 208 | case SortMode::sic: 209 | { 210 | // Well, sorting isn't needed. 211 | } 212 | break; 213 | case SortMode::az: 214 | case SortMode::za: 215 | { 216 | std::vector icu_str_vector; 217 | for (auto& path: rename_vector) 218 | { 219 | icu_str_vector.push_back(icu::UnicodeString(path.first.c_str())); 220 | } 221 | 222 | if (sort_mode == SortMode::az) 223 | { 224 | std::sort(icu_str_vector.begin(), icu_str_vector.end(), [](icu::UnicodeString a, icu::UnicodeString b) {return a < b;}); 225 | }else 226 | if (sort_mode == SortMode::za) 227 | { 228 | std::sort(icu_str_vector.begin(), icu_str_vector.end(), [](icu::UnicodeString a, icu::UnicodeString b) {return a > b;}); 229 | } 230 | 231 | size_t vector_size = rename_vector.size(); 232 | for (size_t counter = 0; counter < vector_size; counter++) 233 | { 234 | std::string path; 235 | icu_str_vector[counter].toUTF8String(path); 236 | rename_vector[counter].first = path; 237 | } 238 | } 239 | break; 240 | } 241 | } 242 | 243 | -------------------------------------------------------------------------------- /AnyOption/anyoption.h: -------------------------------------------------------------------------------- 1 | #ifndef _ANYOPTION_H 2 | #define _ANYOPTION_H 3 | 4 | #define _CRT_SECURE_NO_WARNINGS /* Microsoft C/C++ Compiler: Disable C4996 \ 5 | warnings for security-enhanced CRT \ 6 | functions */ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #define COMMON_OPT 1 15 | #define COMMAND_OPT 2 16 | #define FILE_OPT 3 17 | #define COMMON_FLAG 4 18 | #define COMMAND_FLAG 5 19 | #define FILE_FLAG 6 20 | 21 | #define COMMAND_OPTION_TYPE 1 22 | #define COMMAND_FLAG_TYPE 2 23 | #define FILE_OPTION_TYPE 3 24 | #define FILE_FLAG_TYPE 4 25 | #define UNKNOWN_TYPE 5 26 | 27 | #define DEFAULT_MAXOPTS 10 28 | #define MAX_LONG_PREFIX_LENGTH 2 29 | 30 | #define DEFAULT_MAXUSAGE 3 31 | #define DEFAULT_MAXHELP 10 32 | 33 | #define TRUE_FLAG "true" 34 | 35 | using namespace std; 36 | 37 | class AnyOption { 38 | 39 | public: /* the public interface */ 40 | AnyOption(); 41 | 42 | explicit AnyOption(int maxoptions); 43 | explicit AnyOption(int maxoptions, int maxcharoptions); 44 | ~AnyOption(); 45 | 46 | /* 47 | * following set methods specifies the 48 | * special characters and delimiters 49 | * if not set traditional defaults will be used 50 | */ 51 | 52 | void setCommandPrefixChar(char _prefix); /* '-' in "-w" */ 53 | void setCommandLongPrefix(const char *_prefix); /* '--' in "--width" */ 54 | void setFileCommentChar(char _comment); /* '#' in shell scripts */ 55 | void setFileDelimiterChar(char _delimiter); /* ':' in "width : 100" */ 56 | 57 | /* 58 | * provide the input for the options 59 | * like argv[] for commnd line and the 60 | * option file name to use; 61 | */ 62 | 63 | void useCommandArgs(int _argc, char **_argv); 64 | void useFiileName(const char *_filename); 65 | 66 | /* 67 | * turn off the POSIX style options 68 | * this means anything starting with a '-' or "--" 69 | * will be considered a valid option 70 | * which also means you cannot add a bunch of 71 | * POIX options chars together like "-lr" for "-l -r" 72 | * 73 | */ 74 | 75 | void noPOSIX(); 76 | 77 | /* 78 | * prints warning verbose if you set anything wrong 79 | */ 80 | void setVerbose(); 81 | 82 | /* 83 | * there are two types of options 84 | * 85 | * Option - has an associated value ( -w 100 ) 86 | * Flag - no value, just a boolean flag ( -nogui ) 87 | * 88 | * the options can be either a string ( GNU style ) 89 | * or a character ( traditional POSIX style ) 90 | * or both ( --width, -w ) 91 | * 92 | * the options can be common to the command line and 93 | * the option file, or can belong only to either of 94 | * command line and option file 95 | * 96 | * following set methods, handle all the above 97 | * cases of options. 98 | */ 99 | 100 | /* options command to command line and option file */ 101 | void setOption(const char *opt_string); 102 | void setOption(char opt_char); 103 | void setOption(const char *opt_string, char opt_char); 104 | void setFlag(const char *opt_string); 105 | void setFlag(char opt_char); 106 | void setFlag(const char *opt_string, char opt_char); 107 | 108 | /* options read from command line only */ 109 | void setCommandOption(const char *opt_string); 110 | void setCommandOption(char opt_char); 111 | void setCommandOption(const char *opt_string, char opt_char); 112 | void setCommandFlag(const char *opt_string); 113 | void setCommandFlag(char opt_char); 114 | void setCommandFlag(const char *opt_string, char opt_char); 115 | 116 | /* options read from an option file only */ 117 | void setFileOption(const char *opt_string); 118 | void setFileOption(char opt_char); 119 | void setFileOption(const char *opt_string, char opt_char); 120 | void setFileFlag(const char *opt_string); 121 | void setFileFlag(char opt_char); 122 | void setFileFlag(const char *opt_string, char opt_char); 123 | 124 | /* 125 | * process the options, registered using 126 | * useCommandArgs() and useFileName(); 127 | */ 128 | void processOptions(); 129 | void processCommandArgs(); 130 | void processCommandArgs(int max_args); 131 | bool processFile(); 132 | 133 | /* 134 | * process the specified options 135 | */ 136 | void processCommandArgs(int _argc, char **_argv); 137 | void processCommandArgs(int _argc, char **_argv, int max_args); 138 | bool processFile(const char *_filename); 139 | 140 | /* 141 | * get the value of the options 142 | * will return NULL if no value is set 143 | */ 144 | char *getValue(const char *_option); 145 | bool getFlag(const char *_option); 146 | char *getValue(char _optchar); 147 | bool getFlag(char _optchar); 148 | 149 | /* 150 | * Print Usage 151 | */ 152 | void printUsage(); 153 | void printAutoUsage(); 154 | void addUsage(const char *line); 155 | void printHelp(); 156 | /* print auto usage printing for unknown options or flag */ 157 | void autoUsagePrint(bool flag); 158 | 159 | /* 160 | * get the argument count and arguments sans the options 161 | */ 162 | int getArgc() const; 163 | char *getArgv(int index) const; 164 | bool hasOptions() const; 165 | 166 | private: /* the hidden data structure */ 167 | int argc; /* command line arg count */ 168 | char **argv; /* commnd line args */ 169 | const char *filename; /* the option file */ 170 | char *appname; /* the application name from argv[0] */ 171 | 172 | int *new_argv; /* arguments sans options (index to argv) */ 173 | int new_argc; /* argument count sans the options */ 174 | int max_legal_args; /* ignore extra arguments */ 175 | 176 | /* option strings storage + indexing */ 177 | int max_options; /* maximum number of options */ 178 | const char **options; /* storage */ 179 | int *optiontype; /* type - common, command, file */ 180 | int *optionindex; /* index into value storage */ 181 | int option_counter; /* counter for added options */ 182 | 183 | /* option chars storage + indexing */ 184 | int max_char_options; /* maximum number options */ 185 | char *optionchars; /* storage */ 186 | int *optchartype; /* type - common, command, file */ 187 | int *optcharindex; /* index into value storage */ 188 | int optchar_counter; /* counter for added options */ 189 | 190 | /* values */ 191 | char **values; /* common value storage */ 192 | int g_value_counter; /* globally updated value index LAME! */ 193 | 194 | /* help and usage */ 195 | const char **usage; /* usage */ 196 | int max_usage_lines; /* max usage lines reserved */ 197 | int usage_lines; /* number of usage lines */ 198 | 199 | bool command_set; /* if argc/argv were provided */ 200 | bool file_set; /* if a filename was provided */ 201 | bool mem_allocated; /* if memory allocated in init() */ 202 | bool posix_style; /* enables to turn off POSIX style options */ 203 | bool verbose; /* silent|verbose */ 204 | bool print_usage; /* usage verbose */ 205 | bool print_help; /* help verbose */ 206 | 207 | char opt_prefix_char; /* '-' in "-w" */ 208 | char long_opt_prefix[MAX_LONG_PREFIX_LENGTH + 1]; /* '--' in "--width" */ 209 | char file_delimiter_char; /* ':' in width : 100 */ 210 | char file_comment_char; /* '#' in "#this is a comment" */ 211 | char equalsign; 212 | char comment; 213 | char delimiter; 214 | char endofline; 215 | char whitespace; 216 | char nullterminate; 217 | 218 | bool set; // was static member 219 | bool once; // was static member 220 | 221 | bool hasoptions; 222 | bool autousage; 223 | 224 | private: /* the hidden utils */ 225 | void init(); 226 | void init(int maxopt, int maxcharopt); 227 | bool alloc(); 228 | void allocValues(int index, size_t length); 229 | void cleanup(); 230 | bool valueStoreOK(); 231 | 232 | /* grow storage arrays as required */ 233 | bool doubleOptStorage(); 234 | bool doubleCharStorage(); 235 | bool doubleUsageStorage(); 236 | 237 | bool setValue(const char *option, char *value); 238 | bool setFlagOn(const char *option); 239 | bool setValue(char optchar, char *value); 240 | bool setFlagOn(char optchar); 241 | 242 | void addOption(const char *option, int type); 243 | void addOption(char optchar, int type); 244 | void addOptionError(const char *opt) const; 245 | void addOptionError(char opt) const; 246 | bool findFlag(char *value); 247 | void addUsageError(const char *line); 248 | bool CommandSet() const; 249 | bool FileSet() const; 250 | bool POSIX() const; 251 | 252 | char parsePOSIX(char *arg); 253 | int parseGNU(char *arg); 254 | bool matchChar(char c); 255 | int matchOpt(char *opt); 256 | 257 | /* dot file methods */ 258 | char *readFile(); 259 | char *readFile(const char *fname); 260 | bool consumeFile(char *buffer); 261 | void processLine(char *theline, int length); 262 | char *chomp(char *str); 263 | void valuePairs(char *type, char *value); 264 | void justValue(char *value); 265 | 266 | void printVerbose(const char *msg) const; 267 | void printVerbose(char *msg) const; 268 | void printVerbose(char ch) const; 269 | void printVerbose() const; 270 | }; 271 | 272 | #endif /* ! _ANYOPTION_H */ 273 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | ─────────────────┨ What is this? ┠───────────────── 2 | 3 | Nomenus-rex is a CLI utility for the file mass-renaming. 4 | 5 | ─────────────────┨ Installing ┠───────────────── 6 | You can download the source from the GitHub: 7 | 8 | git clone https://github.com/ANGulchenko/nomenus-rex.git 9 | 10 | Nomenus-rex was created to be assembled with CMake, so just run these commands 11 | from the directory with CMakeLists.txt: 12 | 13 | cmake ./ 14 | make 15 | 16 | ─────────────────┨ How to use? ┠───────────────── 17 | 18 | Nomenus-rex is a typical CLI (command line interface) utility and has such 19 | parameters: 20 | 21 | -h --help Prints short help 22 | -s --source sets the path to the source directory 23 | -d --destination sets the path to the destination directory 24 | -c --config sets the path to the configuration file 25 | -e --example Prints out the example configuration 26 | -y --yes Process files without confirmation 27 | -l --laconic Print only error messages (don't affect process confirmation); 28 | -p --print_limit Limit the amount of bijections printed. 29 | 30 | The only mandatory parameter is "-c"/"--config". Source and destination paths 31 | can be omitted if they're present in the configuration file. If paths are set in 32 | the command line and in the configuration file then command-line data has higher 33 | priority. 34 | It is possible to use "~" char if you have a "HOME" environment variable set 35 | in your system. Also you can omit the full path to the config file. In this case 36 | the config would be searched in XDG_CONFIG_HOME/nomenus-rex/ directory or 37 | (in the case of the absense of XDG_CONFIG_HOME environment variable) in the 38 | HOME/.config/nomenus-rex/ 39 | -e/--example parameter is very convenient for the one-off configurations. Just 40 | move to the desired directory and enter the command like: 41 | nomenus-rex -e > example.conf 42 | This will create the basic config with already filled-in source/destination paths. 43 | 44 | Here is an example of the configuration file (decorative borders aren't 45 | included): 46 | 47 | ─────────────────┨ Start config ┠───────────────── 48 | 49 | source_dir = "/home/user/work/source"; 50 | destination_dir = "/home/user/work/destination"; 51 | 52 | keep_dir_structure = false; 53 | copy_or_rename = "copy"; 54 | sort_mode = "az"; 55 | 56 | rules = ( 57 | { 58 | type = "date"; 59 | date_format = "%Y-%m-%d"; 60 | }, 61 | { 62 | type = "text"; 63 | text = "_"; 64 | }, 65 | { 66 | type = "dir"; 67 | // mode = "whole path"|"parent dir only" 68 | mode = "whole path"; 69 | separator = "-"; 70 | 71 | }, 72 | { 73 | type = "text"; 74 | text = "_"; 75 | }, 76 | { 77 | type = "integer"; 78 | // mode = "global"|"local at every dir" 79 | mode = "local at every dir"; 80 | start = 0; 81 | step = 1; 82 | padding = 5; 83 | }, 84 | { 85 | type = "extension"; 86 | // leave the "ext" variable empty to use an original extension 87 | ext = ""; 88 | // mode = "lowercase"|"uppercase"|"sic"; 89 | mode = "lowercase"; 90 | } 91 | ); 92 | 93 | ─────────────────┨ End config ┠───────────────── 94 | 95 | // is a single-line comment. 96 | /* 97 | Multi-line comment. 98 | */ 99 | 100 | "Source/destination directories" are self-explanatory. You should make them 101 | identical if you want to rename files, but not copy or move. It is possible 102 | to use "~" char if you have a "HOME" environment variable set in your system. 103 | 104 | "keep_dir_structure" can be true or false. While "false", no subdirectories are 105 | created in the destination directory. "True" keeps the subdirectory structure 106 | identical to the source. 107 | 108 | "copy_or_rename" can be "copy" or "rename". In "copy" mode files are copying, in 109 | "rename" they are renaming or moving. 110 | 111 | "sort_mode" controls the sorting of the filenames before processing. Can be "sic" 112 | for no sorting at all, "az" for ascending alphabetical sorting, and "za" for descending 113 | alphabetical sorting. 114 | 115 | "rules" is an array of small templates, each of which is responsible for a particle 116 | of the resulting filename. These templates-rules are processed in the same order 117 | as they are described in the "rules" array. For example, the aforecited config 118 | will copy 119 | "/home/user/work/source/TestDir2/file2.txt" 120 | to something like 121 | "/home/user/work/destination/2022-03-16_TestDir2_00000.txt" 122 | 123 | Rules can be of this types: 124 | 125 | "date" : date_format is the same as in STRFTIME(3) 126 | ────┨ Example ┠──────────────── 127 | { 128 | type = "date"; 129 | date_format = "%Y-%m-%d"; 130 | } 131 | 132 | "filedate" : this is the time of last modification. "date_format" is the same as in STRFTIME(3) 133 | ────┨ Example ┠──────────────── 134 | { 135 | type = "filedate"; 136 | date_format = "%Y-%m-%d"; 137 | } 138 | 139 | "text" : just any text 140 | ────┨ Example ┠──────────────── 141 | { 142 | type = "text"; 143 | text = "_"; 144 | } 145 | 146 | "dir" : mode "whole path" inserts the whole path with subdirs separated 147 | with "separator". 148 | mode "parent dir only" inserts only the nearest parent dir to 149 | the file. 150 | Only works with subdirectories to the source directory. 151 | ────┨ Example ┠──────────────── 152 | { 153 | type = "dir"; 154 | // mode = "whole path"|"parent dir only" 155 | mode = "whole path"; 156 | separator = "-"; 157 | } 158 | 159 | "integer" : inserts the number which starts from "start" and iterates with 160 | "step". 161 | "padding" dictates the length of the result: integer will be padded 162 | with zeros. 163 | mode "global" uses one counter for all files. 164 | mode "local at every dir" uses separate counters for ever subdir. 165 | ────┨ Example ┠──────────────── 166 | { 167 | type = "integer"; 168 | // mode = "global"|"local at every dir" 169 | mode = "local at every dir"; 170 | start = 0; 171 | step = 1; 172 | padding = 5; 173 | } 174 | 175 | "extension": inserts the file extension. By default, it uses the file's 176 | extension or you can provide your own extension through the "ext" 177 | variable. 178 | mode "lowercase" transforms the extension to lowercase. 179 | mode "uppercase" transforms the extension to uppercase. 180 | mode "sic" uses the original case. 181 | ────┨ Example ┠──────────────── 182 | { 183 | type = "extension"; 184 | // leave the "ext" variable empty to use an original extension 185 | ext = ""; 186 | // mode = "lowercase"|"uppercase"|"sic"; 187 | mode = "lowercase"; 188 | } 189 | 190 | "filename" : mode "lowercase" transforms the filename to lowercase. 191 | mode "uppercase" transforms the filename to uppercase. 192 | mode "sic" uses the original case. 193 | ────┨ Example ┠──────────────── 194 | { 195 | type = "filename"; 196 | // mode = "lowercase"|"uppercase"|"sic"; 197 | mode = "lowercase"; 198 | } 199 | 200 | "filesize" : the "dimension" can be "B","KiB","MiB", or "GiB". 201 | the dimension can be hidden with a help of "show_dimension" var. 202 | you can set any decimal separator. The dot wasn't a good idea because 203 | of the messing with file's extension. 204 | ────┨ Example ┠──────────────── 205 | { 206 | type = "filesize"; 207 | // dimension = "B"|"KiB"|"MiB"|"GiB" 208 | dimension = "KiB"; 209 | show_dimension = true; 210 | decimal_separator = ","; 211 | } 212 | 213 | "replace" : replaces all occurences of "what" substring to "to" substring. 214 | The replacement occurs in the current generating filename. For 215 | example, if you want to rename a "BlaBla001.txt" to "Ololo001.txt" 216 | you can use a "filename" rule first to set the current precessing 217 | filename into the "BlaBla001", then use "replace" rule with 218 | what="BlaBla" and to="Ololo" parameters and don't forget about 219 | extension rule in the end. 220 | ────┨ Example ┠──────────────── 221 | { 222 | type = "replace"; 223 | what = "BlaBla"; 224 | to = "Ololo"; 225 | } 226 | 227 | "exec" : Runs the command (FILE *popen(const char *command, const char *type)) 228 | where all occurences of the placeholder are substituted with a filename. 229 | Result of the rule is the stdout output of the command. 230 | ────┨ Example ┠──────────────── 231 | { 232 | type = "exec"; 233 | command = "echo '' | grep -Eo '[0-9]+'"; 234 | placeholder = ""; 235 | } 236 | 237 | 238 | -------------------------------------------------------------------------------- /configurationparser.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "AnyOption/anyoption.h" 4 | #include "configurationparser.h" 5 | #include "version.h" 6 | #include "cfgvarsingleton.h" 7 | 8 | ConfigurationParser::ConfigurationParser(int argc, char *argv[], Renamer& renamer) 9 | { 10 | std::string source; 11 | std::string destination; 12 | std::string config; 13 | 14 | AnyOption opt; 15 | std::string intro_line = "Nomenus-rex("+CfgVarSingleton::Instance().nomenus_ver_str+") is a file mass-renaming utility."; 16 | opt.addUsage(intro_line.c_str()); 17 | opt.addUsage("Parameters: "); 18 | opt.addUsage(""); 19 | opt.addUsage(" -h --help Prints this help "); 20 | opt.addUsage(" -s --source Source dir"); 21 | opt.addUsage(" -d --destination Destination dir"); 22 | opt.addUsage(" -c --config Configuration file"); 23 | opt.addUsage(" -e --example Prints out the example configuration"); 24 | opt.addUsage(" -y --yes Process files without confirmation"); 25 | opt.addUsage(" -l --laconic Print only error messages"); 26 | string print_limit = 27 | " -p --print_limit Limit the amount of bijections printed. "+std::to_string(CfgVarSingleton::Instance().amount_of_bijections_printed)+" by default"; 28 | opt.addUsage(print_limit.c_str()); 29 | opt.addUsage(""); 30 | opt.addUsage("Directories can be also set up in the config file. CLI parameters have higher priority."); 31 | 32 | opt.setFlag("help", 'h'); 33 | opt.setCommandOption("source", 's'); 34 | opt.setCommandOption("destination", 'd'); 35 | opt.setCommandOption("config", 'c'); 36 | opt.setFlag("yes", 'y'); 37 | opt.setFlag("example", 'e'); 38 | opt.setFlag("laconic", 'l'); 39 | opt.setCommandOption("print_limit", 'p'); 40 | 41 | opt.processCommandArgs(argc, argv); 42 | 43 | if (opt.hasOptions()) 44 | { 45 | if (opt.getFlag("help") || opt.getFlag('h')) 46 | { 47 | opt.printUsage(); 48 | exit(EXIT_SUCCESS); 49 | } 50 | 51 | if (opt.getFlag("yes") || opt.getFlag('y')) 52 | { 53 | CfgVarSingleton::Instance().ask_confirmation_for_file_processing = false; 54 | }else 55 | { 56 | CfgVarSingleton::Instance().ask_confirmation_for_file_processing = true; 57 | } 58 | 59 | if (opt.getFlag("laconic") || opt.getFlag('l')) 60 | { 61 | CfgVarSingleton::Instance().verbose = false; 62 | }else 63 | { 64 | CfgVarSingleton::Instance().verbose = true; 65 | } 66 | 67 | if (opt.getFlag("example") || opt.getFlag('e')) 68 | { 69 | printTypicalConfig(); 70 | exit(EXIT_SUCCESS); 71 | } 72 | 73 | if (opt.getValue('s') != NULL || opt.getValue("source") != NULL) 74 | { 75 | source = string(opt.getValue("source")); 76 | } 77 | 78 | if (opt.getValue('d') != NULL || opt.getValue("destination") != NULL) 79 | { 80 | destination = string(opt.getValue("destination")); 81 | } 82 | 83 | if (opt.getValue('c') != NULL || opt.getValue("config") != NULL) 84 | { 85 | config = string(opt.getValue("config")); 86 | } 87 | 88 | if (opt.getValue('p') != NULL || opt.getValue("print_limit") != NULL) 89 | { 90 | CfgVarSingleton::Instance().amount_of_bijections_printed = stoi(string(opt.getValue("print_limit"))); 91 | } 92 | } 93 | 94 | 95 | 96 | if (config == "") 97 | { 98 | std::cerr << "\nERROR: No config file is specified!" << std::endl; 99 | opt.printUsage(); 100 | exit(EXIT_FAILURE); 101 | } 102 | 103 | config = getConfigPathString(config); 104 | 105 | // Parsing the config, creating the Rules objects and putting them into the array. 106 | makeSureThatConfigDirIsExist(); 107 | Config cfg; 108 | 109 | try 110 | { 111 | cfg.readFile(config.c_str()); 112 | } 113 | catch(const FileIOException &fioex) 114 | { 115 | std::cerr << "I/O error while reading configuration file." << std::endl; 116 | exit(EXIT_FAILURE); 117 | } 118 | catch(const ParseException &pex) 119 | { 120 | std::cerr << "Parse error at " << pex.getFile() << ":" << pex.getLine() 121 | << " - " << pex.getError() << std::endl; 122 | exit(EXIT_FAILURE); 123 | } 124 | 125 | const Setting& root = cfg.getRoot(); 126 | 127 | ////////////////////////////////////////////////////////////////////////////// 128 | // Check source/destination dirs. But we must remember that those dirs 129 | // from CLI have bigger priority. 130 | 131 | if (source == "") 132 | { 133 | std::string source_dir_cfg; 134 | if (root.lookupValue("source_dir", source_dir_cfg)) 135 | { 136 | source = {source_dir_cfg}; 137 | }else 138 | { 139 | std::cerr << "\nERROR: There is no 'Source_dir' neither in parameters nor in config file" << std::endl; 140 | exit(EXIT_FAILURE); 141 | } 142 | } 143 | 144 | if (destination == "") 145 | { 146 | std::string destination_dir_cfg; 147 | if (root.lookupValue("destination_dir", destination_dir_cfg)) 148 | { 149 | destination = {destination_dir_cfg}; 150 | }else 151 | { 152 | std::cerr << "\nERROR: There is no 'Destination_dir' neither in parameters nor in config file" << std::endl; 153 | exit(EXIT_FAILURE); 154 | } 155 | } 156 | 157 | // replace ~ with a home dir path if needed 158 | 159 | const char *home = getenv("HOME"); 160 | 161 | if (home) 162 | { 163 | if (size_t tylda = source.find("~"); tylda != std::string::npos) 164 | { 165 | source.replace(tylda, 1, home); 166 | } 167 | 168 | if (size_t tylda = source.find("~"); tylda != std::string::npos) 169 | { 170 | destination.replace(tylda, 1, home); 171 | } 172 | } 173 | 174 | // We should check if "source" exists. Destination doesn't matter -- it'll 175 | // be created while processing anyway. 176 | 177 | if (!filesystem::exists(fs::path(source))) 178 | { 179 | std::cerr << "\nERROR: Source dir("<< source <<") doesn't exist." << std::endl; 180 | exit(EXIT_FAILURE); 181 | } 182 | 183 | renamer.source_dir = source; 184 | renamer.destination_dir = destination; 185 | 186 | ////////////////////////////////////////////////////////////////////////////// 187 | 188 | bool keep_dir_structure = false; 189 | getVar(root, "keep_dir_structure", keep_dir_structure); 190 | renamer.keep_dir_structure = keep_dir_structure; 191 | 192 | Renamer::CopyOrRename copy_or_rename_mode = 193 | enumParser(root, "Config root", "copy_or_rename", 194 | { 195 | {"copy", Renamer::CopyOrRename::copy}, 196 | {"rename", Renamer::CopyOrRename::rename} 197 | }); 198 | renamer.copy_or_rename = copy_or_rename_mode; 199 | 200 | Renamer::SortMode sort_mode = 201 | enumParser(root, "Config root", "sort_mode", 202 | { 203 | {"sic", Renamer::SortMode::sic}, 204 | {"az", Renamer::SortMode::az}, 205 | {"za", Renamer::SortMode::za} 206 | }); 207 | renamer.sort_mode = sort_mode; 208 | 209 | ////////////////////////////////////////////////////////////////////////////// 210 | 211 | const Setting &rules_raw = root["rules"]; 212 | 213 | int count = rules_raw.getLength(); 214 | 215 | std::string rule_type; 216 | for(int i = 0; i < count; ++i) 217 | { 218 | const Setting &rule_raw = rules_raw[i]; 219 | getVar(rule_raw, "type", rule_type); 220 | 221 | //////////////////////////////////////////////////////////////////////// 222 | if (rule_type == "date") 223 | { 224 | std::string date_format; 225 | getRuleVar(rule_raw, "date_format", rule_type, date_format); 226 | //renamer.rules.push_back(std::unique_ptr(new RuleDate(date_format))); 227 | renamer.rules.push_back(std::make_unique(date_format)); 228 | } 229 | ///////////////////////////////////////////////////////////////////////// 230 | else 231 | if (rule_type == "text") 232 | { 233 | std::string text; 234 | getRuleVar(rule_raw, "text", rule_type, text); 235 | renamer.rules.push_back(std::make_unique(text)); 236 | } 237 | ///////////////////////////////////////////////////////////////////////// 238 | else 239 | if (rule_type == "dir") 240 | { 241 | RuleDir::Mode mode = 242 | enumParser(rule_raw, rule_type, "mode", 243 | { 244 | {"whole path", RuleDir::Mode::whole}, 245 | {"parent dir only", RuleDir::Mode::parent_only} 246 | }); 247 | 248 | std::string separator; 249 | getRuleVar(rule_raw, "separator", rule_type, separator); 250 | renamer.rules.push_back(std::make_unique(mode, separator)); 251 | } 252 | ///////////////////////////////////////////////////////////////////////// 253 | else 254 | if (rule_type == "integer") 255 | { 256 | RuleInteger::Mode mode = 257 | enumParser(rule_raw, rule_type, "mode", 258 | { 259 | {"global", RuleInteger::Mode::global}, 260 | {"local at every dir", RuleInteger::Mode::local_at_every_dir} 261 | }); 262 | 263 | int start; 264 | int step; 265 | int padding; 266 | getRuleVar(rule_raw, "start", rule_type, start); 267 | getRuleVar(rule_raw, "step", rule_type, step); 268 | getRuleVar(rule_raw, "padding", rule_type, padding); 269 | 270 | renamer.rules.push_back(std::make_unique(mode, start, step, padding)); 271 | 272 | } 273 | ///////////////////////////////////////////////////////////////////////// 274 | else 275 | if (rule_type == "extension") 276 | { 277 | RuleExtension::Mode mode = 278 | enumParser(rule_raw, rule_type, "mode", 279 | { 280 | {"sic", RuleExtension::Mode::sic}, 281 | {"lowercase", RuleExtension::Mode::lowercase}, 282 | {"uppercase", RuleExtension::Mode::uppercase} 283 | }); 284 | 285 | std::string ext; 286 | getRuleVar(rule_raw, "ext", rule_type, ext); 287 | 288 | renamer.rules.push_back(std::make_unique(mode, ext)); 289 | 290 | } 291 | ///////////////////////////////////////////////////////////////////////// 292 | else 293 | if (rule_type == "filename") 294 | { 295 | RuleFilename::Mode mode = 296 | enumParser(rule_raw, rule_type, "mode", 297 | { 298 | {"sic", RuleFilename::Mode::sic}, 299 | {"lowercase", RuleFilename::Mode::lowercase}, 300 | {"uppercase", RuleFilename::Mode::uppercase} 301 | }); 302 | 303 | renamer.rules.push_back(std::make_unique(mode)); 304 | 305 | } 306 | ///////////////////////////////////////////////////////////////////////// 307 | else 308 | if (rule_type == "filesize") 309 | { 310 | RuleFilesize::Dimension dimension = 311 | enumParser(rule_raw, rule_type, "dimension", 312 | { 313 | {"B", RuleFilesize::Dimension::B}, 314 | {"KiB", RuleFilesize::Dimension::KiB}, 315 | {"MiB", RuleFilesize::Dimension::MiB}, 316 | {"GiB", RuleFilesize::Dimension::GiB} 317 | }); 318 | 319 | 320 | std::string decimal_separator; 321 | bool show_dimension; 322 | getRuleVar(rule_raw, "decimal_separator", rule_type, decimal_separator); 323 | getRuleVar(rule_raw, "show_dimension", rule_type, show_dimension); 324 | 325 | renamer.rules.push_back(std::make_unique(dimension, decimal_separator, show_dimension)); 326 | 327 | } 328 | ///////////////////////////////////////////////////////////////////////// 329 | else 330 | if (rule_type == "filedate") 331 | { 332 | std::string date_format; 333 | getRuleVar(rule_raw, "date_format", rule_type, date_format); 334 | renamer.rules.push_back(std::make_unique(date_format)); 335 | } 336 | ///////////////////////////////////////////////////////////////////////// 337 | else 338 | if (rule_type == "replace") 339 | { 340 | std::string what; 341 | std::string to; 342 | getRuleVar(rule_raw, "what", rule_type, what); 343 | getRuleVar(rule_raw, "to", rule_type, to); 344 | 345 | renamer.rules.push_back(std::make_unique(what, to)); 346 | } 347 | ///////////////////////////////////////////////////////////////////////// 348 | else 349 | if (rule_type == "exec") 350 | { 351 | std::string command; 352 | std::string placeholder; 353 | getRuleVar(rule_raw, "command", rule_type, command); 354 | getRuleVar(rule_raw, "placeholder", rule_type, placeholder); 355 | 356 | renamer.rules.push_back(std::make_unique(command, placeholder)); 357 | } 358 | } 359 | } 360 | 361 | void ConfigurationParser::makeSureThatConfigDirIsExist() 362 | { 363 | if (const char *xdg_config_path = getenv("XDG_CONFIG_HOME"); xdg_config_path) 364 | { 365 | std::string config_dir = {xdg_config_path}; 366 | config_dir += "/nomenus-rex/"; 367 | fs::create_directories(config_dir); 368 | }else 369 | if (const char *home_path = getenv("HOME"); home_path) 370 | { 371 | std::string config_dir = {home_path}; 372 | config_dir += "/.config/nomenus-rex/"; 373 | fs::create_directories(config_dir); 374 | } 375 | } 376 | 377 | std::string ConfigurationParser::getConfigPathString(std::string raw_parameter) 378 | { 379 | // User might give the path to config with a ~ sign. 380 | const char *home = getenv("HOME"); 381 | if (home) 382 | { 383 | if (size_t tylda = raw_parameter.find("~"); tylda != std::string::npos) 384 | { 385 | raw_parameter.replace(tylda, 1, home); 386 | } 387 | } 388 | 389 | // We should check if the user's data is a valid path to the config. 390 | // If not, we should try to assemble something with XDG_CONFIG_HOME/HOME 391 | if (std::filesystem::exists(std::filesystem::path(raw_parameter))) 392 | { 393 | std::cerr << "NOTIFICATION: Using " << raw_parameter << " config file" << std::endl; 394 | return raw_parameter; 395 | }else 396 | { 397 | std::cerr << "ERROR: Config file " << raw_parameter << " doesn't exist" << std::endl; 398 | } 399 | 400 | 401 | //Nah, there isn't such file. 402 | //Let's try with XDG_CONFIG_HOME 403 | 404 | 405 | const char *xdg_home = getenv("XDG_CONFIG_HOME"); 406 | if (xdg_home) 407 | { 408 | const std::string xdg_name = std::string(xdg_home) + std::string("/nomenus-rex/") + raw_parameter; 409 | if (std::filesystem::exists(std::filesystem::path(xdg_name))) 410 | { 411 | std::cerr << "NOTIFICATION: Using " << xdg_name << " config file" << std::endl; 412 | return xdg_name; 413 | }else 414 | { 415 | std::cerr << "ERROR: Config file " << xdg_name << " doesn't exist" << std::endl; 416 | } 417 | } 418 | 419 | // No luck with XDG_CONFIG_HOME. Let's try HOME 420 | if (home) 421 | { 422 | std::string home_name = std::string(home) + std::string("/.config/nomenus-rex/") + raw_parameter; 423 | if (std::filesystem::exists(std::filesystem::path(home_name))) 424 | { 425 | std::cerr << "NOTIFICATION: Using " << home_name << " config file" << std::endl; 426 | return home_name; 427 | }else 428 | { 429 | // No. Just no. We have nowehere elese to look for that file. 430 | std::cerr << "ERROR: Config file " << home_name << " doesn't exist" << std::endl; 431 | std::cerr << "Nowhere else to search for config. Halting." << std::endl; 432 | exit(EXIT_FAILURE); 433 | } 434 | } 435 | 436 | return raw_parameter; 437 | } 438 | 439 | void ConfigurationParser::printTypicalConfig() 440 | { 441 | 442 | fs::path current_path = std::filesystem::current_path(); 443 | cout << "source_dir = " << current_path << ";" << std::endl; 444 | cout << "destination_dir = " << current_path << ";" << std::endl; 445 | 446 | const char* default_config = R"CONFIG( 447 | keep_dir_structure = false; 448 | copy_or_rename = "copy"; 449 | //sort_mode = "az"|"za"|"sic" 450 | sort_mode = "az"; 451 | 452 | rules = ( 453 | { 454 | type = "text"; 455 | text = "PREFIX_"; 456 | }, 457 | { 458 | type = "dir"; 459 | // mode = "whole path"|"parent dir only" 460 | mode = "whole path"; 461 | separator = "-"; 462 | 463 | }, 464 | { 465 | type = "text"; 466 | text = "_"; 467 | }, 468 | { 469 | type = "integer"; 470 | // mode = "global"|"local at every dir" 471 | mode = "local at every dir"; 472 | start = 0; 473 | step = 1; 474 | padding = 5; 475 | }, 476 | { 477 | type = "extension"; 478 | // leave the "ext" variable empty to use an original extension 479 | ext = ""; 480 | // mode = "lowercase"|"uppercase"|"sic"; 481 | mode = "lowercase"; 482 | } 483 | /*{ 484 | type = "date"; 485 | date_format = "%Y-%m-%d"; 486 | },*/ 487 | /*{ 488 | type = "filedate"; 489 | date_format = "%Y-%m-%d"; 490 | },*/ 491 | /*{ 492 | type = "filename"; 493 | // mode = "lowercase"|"uppercase"|"sic"; 494 | mode = "lowercase"; 495 | },*/ 496 | /*{ 497 | type = "filesize"; 498 | // dimension = "B"|"KiB"|"MiB"|"GiB" 499 | dimension = "KiB"; 500 | show_dimension = true; 501 | decimal_separator = ","; 502 | },*/ 503 | /*{ 504 | type = "replace"; 505 | what = "BlaBla"; 506 | to = "Ololo"; 507 | },*/ 508 | /*{ 509 | type = "exec"; 510 | command = "echo '' | grep -Eo '[0-9]+'"; 511 | placeholder = ""; 512 | },*/ 513 | ); 514 | )CONFIG"; 515 | 516 | std::cout << default_config << std::endl; 517 | } 518 | -------------------------------------------------------------------------------- /AnyOption/anyoption.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * AnyOption 1.3 3 | * 4 | * kishan at hackorama dot com www.hackorama.com JULY 2001 5 | * 6 | * + Acts as a common facade class for reading 7 | * command line options as well as options from 8 | * an option file with delimited type value pairs 9 | * 10 | * + Handles the POSIX style single character options ( -w ) 11 | * as well as the newer GNU long options ( --width ) 12 | * 13 | * + The option file assumes the traditional format of 14 | * first character based comment lines and type value 15 | * pairs with a delimiter , and flags which are not pairs 16 | * 17 | * # this is a comment 18 | * # next line is an option value pair 19 | * width : 100 20 | * # next line is a flag 21 | * noimages 22 | * 23 | * + Supports printing out Help and Usage 24 | * 25 | * + Why not just use getopt() ? 26 | * 27 | * getopt() Its a POSIX standard not part of ANSI-C. 28 | * So it may not be available on platforms like Windows. 29 | * 30 | * + Why it is so long ? 31 | * 32 | * The actual code which does command line parsing 33 | * and option file parsing are done in few methods. 34 | * Most of the extra code are for providing a flexible 35 | * common public interface to both a resource file 36 | * and command line supporting POSIX style and 37 | * GNU long option as well as mixing of both. 38 | * 39 | * + Please see "anyoption.h" for public method descriptions 40 | * 41 | */ 42 | 43 | /* Updated August 2004 44 | * Fix from Michael D Peters (mpeters at sandia.gov) 45 | * to remove static local variables, allowing multiple instantiations 46 | * of the reader (for using multiple configuration files). There is 47 | * an error in the destructor when using multiple instances, so you 48 | * cannot delete your objects (it will crash), but not calling the 49 | * destructor only introduces a small memory leak, so I 50 | * have not bothered tracking it down. 51 | * 52 | * Also updated to use modern C++ style headers, rather than 53 | * deprecated iostream.h (it was causing my compiler problems) 54 | */ 55 | 56 | /* 57 | * Updated September 2006 58 | * Fix from Boyan Asenov for a bug in mixing up option indexes 59 | * leading to exception when mixing different options types 60 | */ 61 | 62 | #include "anyoption.h" 63 | 64 | AnyOption::AnyOption() { init(); } 65 | 66 | AnyOption::AnyOption(int maxopt) { init(maxopt, maxopt); } 67 | 68 | AnyOption::AnyOption(int maxopt, int maxcharopt) { init(maxopt, maxcharopt); } 69 | 70 | AnyOption::~AnyOption() { 71 | if (mem_allocated) 72 | cleanup(); 73 | } 74 | 75 | void AnyOption::init() { init(DEFAULT_MAXOPTS, DEFAULT_MAXOPTS); } 76 | 77 | void AnyOption::init(int maxopt, int maxcharopt) { 78 | 79 | max_options = maxopt; 80 | max_char_options = maxcharopt; 81 | max_usage_lines = DEFAULT_MAXUSAGE; 82 | usage_lines = 0; 83 | argc = 0; 84 | argv = NULL; 85 | posix_style = true; 86 | verbose = false; 87 | filename = NULL; 88 | appname = NULL; 89 | option_counter = 0; 90 | optchar_counter = 0; 91 | new_argv = NULL; 92 | new_argc = 0; 93 | max_legal_args = 0; 94 | command_set = false; 95 | file_set = false; 96 | values = NULL; 97 | g_value_counter = 0; 98 | mem_allocated = false; 99 | opt_prefix_char = '-'; 100 | file_delimiter_char = ':'; 101 | file_comment_char = '#'; 102 | equalsign = '='; 103 | comment = '#'; 104 | delimiter = ':'; 105 | endofline = '\n'; 106 | whitespace = ' '; 107 | nullterminate = '\0'; 108 | set = false; 109 | once = true; 110 | hasoptions = false; 111 | autousage = false; 112 | print_usage = false; 113 | print_help = false; 114 | 115 | strcpy(long_opt_prefix, "--"); 116 | 117 | if (alloc() == false) { 118 | cout << endl << "OPTIONS ERROR : Failed allocating memory"; 119 | cout << endl; 120 | cout << "Exiting." << endl; 121 | exit(0); 122 | } 123 | } 124 | 125 | bool AnyOption::alloc() { 126 | int i = 0; 127 | int size = 0; 128 | 129 | if (mem_allocated) 130 | return true; 131 | 132 | size = (max_options + 1) * sizeof(const char *); 133 | options = (const char **)malloc(size); 134 | optiontype = (int *)malloc((max_options + 1) * sizeof(int)); 135 | optionindex = (int *)malloc((max_options + 1) * sizeof(int)); 136 | if (options == NULL || optiontype == NULL || optionindex == NULL) 137 | return false; 138 | else 139 | mem_allocated = true; 140 | for (i = 0; i < max_options; i++) { 141 | options[i] = NULL; 142 | optiontype[i] = 0; 143 | optionindex[i] = -1; 144 | } 145 | optionchars = (char *)malloc((max_char_options + 1) * sizeof(char)); 146 | optchartype = (int *)malloc((max_char_options + 1) * sizeof(int)); 147 | optcharindex = (int *)malloc((max_char_options + 1) * sizeof(int)); 148 | if (optionchars == NULL || optchartype == NULL || optcharindex == NULL) { 149 | mem_allocated = false; 150 | return false; 151 | } 152 | for (i = 0; i < max_char_options; i++) { 153 | optionchars[i] = '0'; 154 | optchartype[i] = 0; 155 | optcharindex[i] = -1; 156 | } 157 | 158 | size = (max_usage_lines + 1) * sizeof(const char *); 159 | usage = (const char **)malloc(size); 160 | 161 | if (usage == NULL) { 162 | mem_allocated = false; 163 | return false; 164 | } 165 | for (i = 0; i < max_usage_lines; i++) 166 | usage[i] = NULL; 167 | 168 | return true; 169 | } 170 | 171 | void AnyOption::allocValues(int index, size_t length) { 172 | if (values[index] == NULL) { 173 | values[index] = (char *)malloc(length); 174 | } else { 175 | free(values[index]); 176 | values[index] = (char *)malloc(length); 177 | } 178 | } 179 | 180 | bool AnyOption::doubleOptStorage() { 181 | const char **options_saved = options; 182 | options = (const char **)realloc(options, ((2 * max_options) + 1) * 183 | sizeof(const char *)); 184 | if (options == NULL) { 185 | free(options_saved); 186 | return false; 187 | } 188 | int *optiontype_saved = optiontype; 189 | optiontype = 190 | (int *)realloc(optiontype, ((2 * max_options) + 1) * sizeof(int)); 191 | if (optiontype == NULL) { 192 | free(optiontype_saved); 193 | return false; 194 | } 195 | int *optionindex_saved = optionindex; 196 | optionindex = 197 | (int *)realloc(optionindex, ((2 * max_options) + 1) * sizeof(int)); 198 | if (optionindex == NULL) { 199 | free(optionindex_saved); 200 | return false; 201 | } 202 | /* init new storage */ 203 | for (int i = max_options; i < 2 * max_options; i++) { 204 | options[i] = NULL; 205 | optiontype[i] = 0; 206 | optionindex[i] = -1; 207 | } 208 | max_options = 2 * max_options; 209 | return true; 210 | } 211 | 212 | bool AnyOption::doubleCharStorage() { 213 | char *optionchars_saved = optionchars; 214 | optionchars = 215 | (char *)realloc(optionchars, ((2 * max_char_options) + 1) * sizeof(char)); 216 | if (optionchars == NULL) { 217 | free(optionchars_saved); 218 | return false; 219 | } 220 | int *optchartype_saved = optchartype; 221 | optchartype = 222 | (int *)realloc(optchartype, ((2 * max_char_options) + 1) * sizeof(int)); 223 | if (optchartype == NULL) { 224 | free(optchartype_saved); 225 | return false; 226 | } 227 | int *optcharindex_saved = optcharindex; 228 | optcharindex = 229 | (int *)realloc(optcharindex, ((2 * max_char_options) + 1) * sizeof(int)); 230 | if (optcharindex == NULL) { 231 | free(optcharindex_saved); 232 | return false; 233 | } 234 | /* init new storage */ 235 | for (int i = max_char_options; i < 2 * max_char_options; i++) { 236 | optionchars[i] = '0'; 237 | optchartype[i] = 0; 238 | optcharindex[i] = -1; 239 | } 240 | max_char_options = 2 * max_char_options; 241 | return true; 242 | } 243 | 244 | bool AnyOption::doubleUsageStorage() { 245 | const char **usage_saved = usage; 246 | usage = (const char **)realloc(usage, ((2 * max_usage_lines) + 1) * 247 | sizeof(const char *)); 248 | if (usage == NULL) { 249 | free(usage_saved); 250 | return false; 251 | } 252 | for (int i = max_usage_lines; i < 2 * max_usage_lines; i++) 253 | usage[i] = NULL; 254 | max_usage_lines = 2 * max_usage_lines; 255 | return true; 256 | } 257 | 258 | void AnyOption::cleanup() { 259 | free(options); 260 | free(optiontype); 261 | free(optionindex); 262 | free(optionchars); 263 | free(optchartype); 264 | free(optcharindex); 265 | free(usage); 266 | if (values != NULL) { 267 | for (int i = 0; i < g_value_counter; i++) { 268 | free(values[i]); 269 | values[i] = NULL; 270 | } 271 | free(values); 272 | } 273 | if (new_argv != NULL) 274 | free(new_argv); 275 | } 276 | 277 | void AnyOption::setCommandPrefixChar(char _prefix) { 278 | opt_prefix_char = _prefix; 279 | } 280 | 281 | void AnyOption::setCommandLongPrefix(const char *_prefix) { 282 | if (strlen(_prefix) > MAX_LONG_PREFIX_LENGTH) { 283 | strncpy(long_opt_prefix, _prefix, MAX_LONG_PREFIX_LENGTH); 284 | long_opt_prefix[MAX_LONG_PREFIX_LENGTH] = nullterminate; 285 | } else { 286 | strcpy(long_opt_prefix, _prefix); 287 | } 288 | } 289 | 290 | void AnyOption::setFileCommentChar(char _comment) { 291 | file_delimiter_char = _comment; 292 | } 293 | 294 | void AnyOption::setFileDelimiterChar(char _delimiter) { 295 | file_comment_char = _delimiter; 296 | } 297 | 298 | bool AnyOption::CommandSet() const { return (command_set); } 299 | 300 | bool AnyOption::FileSet() const { return (file_set); } 301 | 302 | void AnyOption::noPOSIX() { posix_style = false; } 303 | 304 | bool AnyOption::POSIX() const { return posix_style; } 305 | 306 | void AnyOption::setVerbose() { verbose = true; } 307 | 308 | void AnyOption::printVerbose() const { 309 | if (verbose) 310 | cout << endl; 311 | } 312 | void AnyOption::printVerbose(const char *msg) const { 313 | if (verbose) 314 | cout << msg; 315 | } 316 | 317 | void AnyOption::printVerbose(char *msg) const { 318 | if (verbose) 319 | cout << msg; 320 | } 321 | 322 | void AnyOption::printVerbose(char ch) const { 323 | if (verbose) 324 | cout << ch; 325 | } 326 | 327 | bool AnyOption::hasOptions() const { return hasoptions; } 328 | 329 | void AnyOption::autoUsagePrint(bool _autousage) { autousage = _autousage; } 330 | 331 | void AnyOption::useCommandArgs(int _argc, char **_argv) { 332 | argc = _argc; 333 | argv = _argv; 334 | command_set = true; 335 | appname = argv[0]; 336 | if (argc > 1) 337 | hasoptions = true; 338 | } 339 | 340 | void AnyOption::useFiileName(const char *_filename) { 341 | filename = _filename; 342 | file_set = true; 343 | } 344 | 345 | /* 346 | * set methods for options 347 | */ 348 | 349 | void AnyOption::setCommandOption(const char *opt) { 350 | addOption(opt, COMMAND_OPT); 351 | g_value_counter++; 352 | } 353 | 354 | void AnyOption::setCommandOption(char opt) { 355 | addOption(opt, COMMAND_OPT); 356 | g_value_counter++; 357 | } 358 | 359 | void AnyOption::setCommandOption(const char *opt, char optchar) { 360 | addOption(opt, COMMAND_OPT); 361 | addOption(optchar, COMMAND_OPT); 362 | g_value_counter++; 363 | } 364 | 365 | void AnyOption::setCommandFlag(const char *opt) { 366 | addOption(opt, COMMAND_FLAG); 367 | g_value_counter++; 368 | } 369 | 370 | void AnyOption::setCommandFlag(char opt) { 371 | addOption(opt, COMMAND_FLAG); 372 | g_value_counter++; 373 | } 374 | 375 | void AnyOption::setCommandFlag(const char *opt, char optchar) { 376 | addOption(opt, COMMAND_FLAG); 377 | addOption(optchar, COMMAND_FLAG); 378 | g_value_counter++; 379 | } 380 | 381 | void AnyOption::setFileOption(const char *opt) { 382 | addOption(opt, FILE_OPT); 383 | g_value_counter++; 384 | } 385 | 386 | void AnyOption::setFileOption(char opt) { 387 | addOption(opt, FILE_OPT); 388 | g_value_counter++; 389 | } 390 | 391 | void AnyOption::setFileOption(const char *opt, char optchar) { 392 | addOption(opt, FILE_OPT); 393 | addOption(optchar, FILE_OPT); 394 | g_value_counter++; 395 | } 396 | 397 | void AnyOption::setFileFlag(const char *opt) { 398 | addOption(opt, FILE_FLAG); 399 | g_value_counter++; 400 | } 401 | 402 | void AnyOption::setFileFlag(char opt) { 403 | addOption(opt, FILE_FLAG); 404 | g_value_counter++; 405 | } 406 | 407 | void AnyOption::setFileFlag(const char *opt, char optchar) { 408 | addOption(opt, FILE_FLAG); 409 | addOption(optchar, FILE_FLAG); 410 | g_value_counter++; 411 | } 412 | 413 | void AnyOption::setOption(const char *opt) { 414 | addOption(opt, COMMON_OPT); 415 | g_value_counter++; 416 | } 417 | 418 | void AnyOption::setOption(char opt) { 419 | addOption(opt, COMMON_OPT); 420 | g_value_counter++; 421 | } 422 | 423 | void AnyOption::setOption(const char *opt, char optchar) { 424 | addOption(opt, COMMON_OPT); 425 | addOption(optchar, COMMON_OPT); 426 | g_value_counter++; 427 | } 428 | 429 | void AnyOption::setFlag(const char *opt) { 430 | addOption(opt, COMMON_FLAG); 431 | g_value_counter++; 432 | } 433 | 434 | void AnyOption::setFlag(const char opt) { 435 | addOption(opt, COMMON_FLAG); 436 | g_value_counter++; 437 | } 438 | 439 | void AnyOption::setFlag(const char *opt, char optchar) { 440 | addOption(opt, COMMON_FLAG); 441 | addOption(optchar, COMMON_FLAG); 442 | g_value_counter++; 443 | } 444 | 445 | void AnyOption::addOption(const char *opt, int type) { 446 | if (option_counter >= max_options) { 447 | if (doubleOptStorage() == false) { 448 | addOptionError(opt); 449 | return; 450 | } 451 | } 452 | options[option_counter] = opt; 453 | optiontype[option_counter] = type; 454 | optionindex[option_counter] = g_value_counter; 455 | option_counter++; 456 | } 457 | 458 | void AnyOption::addOption(char opt, int type) { 459 | if (!POSIX()) { 460 | printVerbose("Ignoring the option character \""); 461 | printVerbose(opt); 462 | printVerbose("\" ( POSIX options are turned off )"); 463 | printVerbose(); 464 | return; 465 | } 466 | 467 | if (optchar_counter >= max_char_options) { 468 | if (doubleCharStorage() == false) { 469 | addOptionError(opt); 470 | return; 471 | } 472 | } 473 | optionchars[optchar_counter] = opt; 474 | optchartype[optchar_counter] = type; 475 | optcharindex[optchar_counter] = g_value_counter; 476 | optchar_counter++; 477 | } 478 | 479 | void AnyOption::addOptionError(const char *opt) const { 480 | cout << endl; 481 | cout << "OPTIONS ERROR : Failed allocating extra memory " << endl; 482 | cout << "While adding the option : \"" << opt << "\"" << endl; 483 | cout << "Exiting." << endl; 484 | cout << endl; 485 | exit(0); 486 | } 487 | 488 | void AnyOption::addOptionError(char opt) const { 489 | cout << endl; 490 | cout << "OPTIONS ERROR : Failed allocating extra memory " << endl; 491 | cout << "While adding the option: \"" << opt << "\"" << endl; 492 | cout << "Exiting." << endl; 493 | cout << endl; 494 | exit(0); 495 | } 496 | 497 | void AnyOption::processOptions() { 498 | if (!valueStoreOK()) 499 | return; 500 | } 501 | 502 | void AnyOption::processCommandArgs(int max_args) { 503 | max_legal_args = max_args; 504 | processCommandArgs(); 505 | } 506 | 507 | void AnyOption::processCommandArgs(int _argc, char **_argv, int max_args) { 508 | max_legal_args = max_args; 509 | processCommandArgs(_argc, _argv); 510 | } 511 | 512 | void AnyOption::processCommandArgs(int _argc, char **_argv) { 513 | useCommandArgs(_argc, _argv); 514 | processCommandArgs(); 515 | } 516 | 517 | void AnyOption::processCommandArgs() { 518 | if (!(valueStoreOK() && CommandSet())) 519 | return; 520 | 521 | if (max_legal_args == 0) 522 | max_legal_args = argc; 523 | new_argv = (int *)malloc((max_legal_args + 1) * sizeof(int)); 524 | for (int i = 1; i < argc; i++) { /* ignore first argv */ 525 | if (argv[i][0] == long_opt_prefix[0] && 526 | argv[i][1] == long_opt_prefix[1]) { /* long GNU option */ 527 | int match_at = parseGNU(argv[i] + 2); /* skip -- */ 528 | if (match_at >= 0 && i < argc - 1) /* found match */ 529 | setValue(options[match_at], argv[++i]); 530 | } else if (argv[i][0] == opt_prefix_char) { /* POSIX char */ 531 | if (POSIX()) { 532 | char ch = parsePOSIX(argv[i] + 1); /* skip - */ 533 | if (ch != '0' && i < argc - 1) /* matching char */ 534 | setValue(ch, argv[++i]); 535 | } else { /* treat it as GNU option with a - */ 536 | int match_at = parseGNU(argv[i] + 1); /* skip - */ 537 | if (match_at >= 0 && i < argc - 1) /* found match */ 538 | setValue(options[match_at], argv[++i]); 539 | } 540 | } else { /* not option but an argument keep index */ 541 | if (new_argc < max_legal_args) { 542 | new_argv[new_argc] = i; 543 | new_argc++; 544 | } else { /* ignore extra arguments */ 545 | printVerbose("Ignoring extra argument: "); 546 | printVerbose(argv[i]); 547 | printVerbose(); 548 | printAutoUsage(); 549 | } 550 | printVerbose("Unknown command argument option : "); 551 | printVerbose(argv[i]); 552 | printVerbose(); 553 | printAutoUsage(); 554 | } 555 | } 556 | } 557 | 558 | char AnyOption::parsePOSIX(char *arg) { 559 | 560 | for (unsigned int i = 0; i < strlen(arg); i++) { 561 | char ch = arg[i]; 562 | if (matchChar(ch)) { /* keep matching flags till an option */ 563 | /*if last char argv[++i] is the value */ 564 | if (i == strlen(arg) - 1) { 565 | return ch; 566 | } else { /* else the rest of arg is the value */ 567 | i++; /* skip any '=' and ' ' */ 568 | while (arg[i] == whitespace || arg[i] == equalsign) 569 | i++; 570 | setValue(ch, arg + i); 571 | return '0'; 572 | } 573 | } 574 | } 575 | printVerbose("Unknown command argument option : "); 576 | printVerbose(arg); 577 | printVerbose(); 578 | printAutoUsage(); 579 | return '0'; 580 | } 581 | 582 | int AnyOption::parseGNU(char *arg) { 583 | size_t split_at = 0; 584 | /* if has a '=' sign get value */ 585 | for (size_t i = 0; i < strlen(arg); i++) { 586 | if (arg[i] == equalsign) { 587 | split_at = i; /* store index */ 588 | i = strlen(arg); /* get out of loop */ 589 | } 590 | } 591 | if (split_at > 0) { /* it is an option value pair */ 592 | char *tmp = (char *)malloc((split_at + 1) * sizeof(char)); 593 | for (size_t i = 0; i < split_at; i++) 594 | tmp[i] = arg[i]; 595 | tmp[split_at] = '\0'; 596 | 597 | if (matchOpt(tmp) >= 0) { 598 | setValue(options[matchOpt(tmp)], arg + split_at + 1); 599 | free(tmp); 600 | } else { 601 | printVerbose("Unknown command argument option : "); 602 | printVerbose(arg); 603 | printVerbose(); 604 | printAutoUsage(); 605 | free(tmp); 606 | return -1; 607 | } 608 | } else { /* regular options with no '=' sign */ 609 | return matchOpt(arg); 610 | } 611 | return -1; 612 | } 613 | 614 | int AnyOption::matchOpt(char *opt) { 615 | for (int i = 0; i < option_counter; i++) { 616 | if (strcmp(options[i], opt) == 0) { 617 | if (optiontype[i] == COMMON_OPT || 618 | optiontype[i] == COMMAND_OPT) { /* found option return index */ 619 | return i; 620 | } else if (optiontype[i] == COMMON_FLAG || 621 | optiontype[i] == COMMAND_FLAG) { /* found flag, set it */ 622 | setFlagOn(opt); 623 | return -1; 624 | } 625 | } 626 | } 627 | printVerbose("Unknown command argument option : "); 628 | printVerbose(opt); 629 | printVerbose(); 630 | printAutoUsage(); 631 | return -1; 632 | } 633 | bool AnyOption::matchChar(char c) { 634 | for (int i = 0; i < optchar_counter; i++) { 635 | if (optionchars[i] == c) { /* found match */ 636 | if (optchartype[i] == COMMON_OPT || 637 | optchartype[i] == 638 | COMMAND_OPT) { /* an option store and stop scanning */ 639 | return true; 640 | } else if (optchartype[i] == COMMON_FLAG || 641 | optchartype[i] == 642 | COMMAND_FLAG) { /* a flag store and keep scanning */ 643 | setFlagOn(c); 644 | return false; 645 | } 646 | } 647 | } 648 | printVerbose("Unknown command argument option : "); 649 | printVerbose(c); 650 | printVerbose(); 651 | printAutoUsage(); 652 | return false; 653 | } 654 | 655 | bool AnyOption::valueStoreOK() { 656 | if (!set) { 657 | if (g_value_counter > 0) { 658 | const int size = g_value_counter * sizeof(char *); 659 | values = (char **)malloc(size); 660 | for (int i = 0; i < g_value_counter; i++) 661 | values[i] = NULL; 662 | set = true; 663 | } 664 | } 665 | return set; 666 | } 667 | 668 | /* 669 | * public get methods 670 | */ 671 | char *AnyOption::getValue(const char *option) { 672 | if (!valueStoreOK()) 673 | return NULL; 674 | 675 | for (int i = 0; i < option_counter; i++) { 676 | if (strcmp(options[i], option) == 0) 677 | return values[optionindex[i]]; 678 | } 679 | return NULL; 680 | } 681 | 682 | bool AnyOption::getFlag(const char *option) { 683 | if (!valueStoreOK()) 684 | return false; 685 | for (int i = 0; i < option_counter; i++) { 686 | if (strcmp(options[i], option) == 0) 687 | return findFlag(values[optionindex[i]]); 688 | } 689 | return false; 690 | } 691 | 692 | char *AnyOption::getValue(char option) { 693 | if (!valueStoreOK()) 694 | return NULL; 695 | for (int i = 0; i < optchar_counter; i++) { 696 | if (optionchars[i] == option) 697 | return values[optcharindex[i]]; 698 | } 699 | return NULL; 700 | } 701 | 702 | bool AnyOption::getFlag(char option) { 703 | if (!valueStoreOK()) 704 | return false; 705 | for (int i = 0; i < optchar_counter; i++) { 706 | if (optionchars[i] == option) 707 | return findFlag(values[optcharindex[i]]); 708 | } 709 | return false; 710 | } 711 | 712 | bool AnyOption::findFlag(char *val) { 713 | if (val == NULL) 714 | return false; 715 | 716 | if (strcmp(TRUE_FLAG, val) == 0) 717 | return true; 718 | 719 | return false; 720 | } 721 | 722 | /* 723 | * private set methods 724 | */ 725 | bool AnyOption::setValue(const char *option, char *value) { 726 | if (!valueStoreOK()) 727 | return false; 728 | for (int i = 0; i < option_counter; i++) { 729 | if (strcmp(options[i], option) == 0) { 730 | size_t length = (strlen(value) + 1) * sizeof(char); 731 | allocValues(optionindex[i], length); 732 | strncpy(values[optionindex[i]], value, length); 733 | return true; 734 | } 735 | } 736 | return false; 737 | } 738 | 739 | bool AnyOption::setFlagOn(const char *option) { 740 | if (!valueStoreOK()) 741 | return false; 742 | for (int i = 0; i < option_counter; i++) { 743 | if (strcmp(options[i], option) == 0) { 744 | size_t length = (strlen(TRUE_FLAG) + 1) * sizeof(char); 745 | allocValues(optionindex[i], length); 746 | strncpy(values[optionindex[i]], TRUE_FLAG, length); 747 | return true; 748 | } 749 | } 750 | return false; 751 | } 752 | 753 | bool AnyOption::setValue(char option, char *value) { 754 | if (!valueStoreOK()) 755 | return false; 756 | for (int i = 0; i < optchar_counter; i++) { 757 | if (optionchars[i] == option) { 758 | size_t length = (strlen(value) + 1) * sizeof(char); 759 | allocValues(optcharindex[i], length); 760 | strncpy(values[optcharindex[i]], value, length); 761 | return true; 762 | } 763 | } 764 | return false; 765 | } 766 | 767 | bool AnyOption::setFlagOn(char option) { 768 | if (!valueStoreOK()) 769 | return false; 770 | for (int i = 0; i < optchar_counter; i++) { 771 | if (optionchars[i] == option) { 772 | size_t length = (strlen(TRUE_FLAG) + 1) * sizeof(char); 773 | allocValues(optcharindex[i], length); 774 | strncpy(values[optcharindex[i]], TRUE_FLAG, length); 775 | return true; 776 | } 777 | } 778 | return false; 779 | } 780 | 781 | int AnyOption::getArgc() const { return new_argc; } 782 | 783 | char *AnyOption::getArgv(int index) const { 784 | if (index < new_argc) { 785 | return (argv[new_argv[index]]); 786 | } 787 | return NULL; 788 | } 789 | 790 | /* option file sub routines */ 791 | 792 | bool AnyOption::processFile() { 793 | if (!(valueStoreOK() && FileSet())) 794 | return false; 795 | return hasoptions = (consumeFile(readFile())); 796 | } 797 | 798 | bool AnyOption::processFile(const char *_filename) { 799 | useFiileName(_filename); 800 | return (processFile()); 801 | } 802 | 803 | char *AnyOption::readFile() { return (readFile(filename)); } 804 | 805 | /* 806 | * read the file contents to a character buffer 807 | */ 808 | 809 | char *AnyOption::readFile(const char *fname) { 810 | char *buffer; 811 | ifstream is; 812 | is.open(fname, ifstream::in); 813 | if (!is.good()) { 814 | is.close(); 815 | return NULL; 816 | } 817 | is.seekg(0, ios::end); 818 | size_t length = (size_t)is.tellg(); 819 | is.seekg(0, ios::beg); 820 | buffer = (char *)malloc((length + 1) * sizeof(char)); 821 | is.read(buffer, length); 822 | is.close(); 823 | buffer[length] = nullterminate; 824 | return buffer; 825 | } 826 | 827 | /* 828 | * scans a char* buffer for lines that does not 829 | * start with the specified comment character. 830 | */ 831 | bool AnyOption::consumeFile(char *buffer) { 832 | 833 | if (buffer == NULL) 834 | return false; 835 | 836 | char *cursor = buffer; /* preserve the ptr */ 837 | char *pline = NULL; 838 | int linelength = 0; 839 | bool newline = true; 840 | for (unsigned int i = 0; i < strlen(buffer); i++) { 841 | if (*cursor == endofline) { /* end of line */ 842 | if (pline != NULL) /* valid line */ 843 | processLine(pline, linelength); 844 | pline = NULL; 845 | newline = true; 846 | } else if (newline) { /* start of line */ 847 | newline = false; 848 | if ((*cursor != comment)) { /* not a comment */ 849 | pline = cursor; 850 | linelength = 0; 851 | } 852 | } 853 | cursor++; /* keep moving */ 854 | linelength++; 855 | } 856 | free(buffer); 857 | return true; 858 | } 859 | 860 | /* 861 | * find a valid type value pair separated by a delimiter 862 | * character and pass it to valuePairs() 863 | * any line which is not valid will be considered a value 864 | * and will get passed on to justValue() 865 | * 866 | * assuming delimiter is ':' the behaviour will be, 867 | * 868 | * width:10 - valid pair valuePairs( width, 10 ); 869 | * width : 10 - valid pair valuepairs( width, 10 ); 870 | * 871 | * :::: - not valid 872 | * width - not valid 873 | * :10 - not valid 874 | * width: - not valid 875 | * :: - not valid 876 | * : - not valid 877 | * 878 | */ 879 | 880 | void AnyOption::processLine(char *theline, int length) { 881 | char *pline = (char *)malloc((length + 1) * sizeof(char)); 882 | for (int i = 0; i < length; i++) 883 | pline[i] = *(theline++); 884 | pline[length] = nullterminate; 885 | char *cursor = pline; /* preserve the ptr */ 886 | if (*cursor == delimiter || *(cursor + length - 1) == delimiter) { 887 | justValue(pline); /* line with start/end delimiter */ 888 | } else { 889 | bool found = false; 890 | for (int i = 1; i < length - 1 && !found; i++) { /* delimiter */ 891 | if (*cursor == delimiter) { 892 | *(cursor - 1) = nullterminate; /* two strings */ 893 | found = true; 894 | valuePairs(pline, cursor + 1); 895 | } 896 | cursor++; 897 | } 898 | cursor++; 899 | if (!found) /* not a pair */ 900 | justValue(pline); 901 | } 902 | free(pline); 903 | } 904 | 905 | /* 906 | * removes trailing and preceding white spaces from a string 907 | */ 908 | char *AnyOption::chomp(char *str) { 909 | while (*str == whitespace) 910 | str++; 911 | char *end = str + strlen(str) - 1; 912 | while (*end == whitespace) 913 | end--; 914 | *(end + 1) = nullterminate; 915 | return str; 916 | } 917 | 918 | void AnyOption::valuePairs(char *type, char *value) { 919 | if (strlen(chomp(type)) == 1) { /* this is a char option */ 920 | for (int i = 0; i < optchar_counter; i++) { 921 | if (optionchars[i] == type[0]) { /* match */ 922 | if (optchartype[i] == COMMON_OPT || optchartype[i] == FILE_OPT) { 923 | setValue(type[0], chomp(value)); 924 | return; 925 | } 926 | } 927 | } 928 | } 929 | /* if no char options matched */ 930 | for (int i = 0; i < option_counter; i++) { 931 | if (strcmp(options[i], type) == 0) { /* match */ 932 | if (optiontype[i] == COMMON_OPT || optiontype[i] == FILE_OPT) { 933 | setValue(type, chomp(value)); 934 | return; 935 | } 936 | } 937 | } 938 | printVerbose("Unknown option in resource file : "); 939 | printVerbose(type); 940 | printVerbose(); 941 | } 942 | 943 | void AnyOption::justValue(char *type) { 944 | 945 | if (strlen(chomp(type)) == 1) { /* this is a char option */ 946 | for (int i = 0; i < optchar_counter; i++) { 947 | if (optionchars[i] == type[0]) { /* match */ 948 | if (optchartype[i] == COMMON_FLAG || optchartype[i] == FILE_FLAG) { 949 | setFlagOn(type[0]); 950 | return; 951 | } 952 | } 953 | } 954 | } 955 | /* if no char options matched */ 956 | for (int i = 0; i < option_counter; i++) { 957 | if (strcmp(options[i], type) == 0) { /* match */ 958 | if (optiontype[i] == COMMON_FLAG || optiontype[i] == FILE_FLAG) { 959 | setFlagOn(type); 960 | return; 961 | } 962 | } 963 | } 964 | printVerbose("Unknown option in resource file : "); 965 | printVerbose(type); 966 | printVerbose(); 967 | } 968 | 969 | /* 970 | * usage and help 971 | */ 972 | 973 | void AnyOption::printAutoUsage() { 974 | if (autousage) 975 | printUsage(); 976 | } 977 | 978 | void AnyOption::printUsage() { 979 | 980 | if (once) { 981 | once = false; 982 | cout << endl; 983 | for (int i = 0; i < usage_lines; i++) 984 | cout << usage[i] << endl; 985 | cout << endl; 986 | } 987 | } 988 | 989 | void AnyOption::addUsage(const char *line) { 990 | if (usage_lines >= max_usage_lines) { 991 | if (doubleUsageStorage() == false) { 992 | addUsageError(line); 993 | exit(1); 994 | } 995 | } 996 | usage[usage_lines] = line; 997 | usage_lines++; 998 | } 999 | 1000 | void AnyOption::addUsageError(const char *line) { 1001 | cout << endl; 1002 | cout << "OPTIONS ERROR : Failed allocating extra memory " << endl; 1003 | cout << "While adding the usage/help : \"" << line << "\"" << endl; 1004 | cout << "Exiting." << endl; 1005 | cout << endl; 1006 | exit(0); 1007 | } 1008 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------