Beispiel #1
0
 def create(self) -> NoReturn:
     """
     Create the structure of the project.
     """
     super().create()
     self.setup_environment()
     py_file = PythonFile(self.path, "main")
     test_dir = Folder(os.path.join(self.path, 'tests'))
     py_test_file = PythonFile(os.path.join(self.path, 'tests'),
                               'test_main')
     py_test_file.write(
         "import unittest\n\nfrom main import main\n\n\nclass MainTest(unittest.TestCase):\n    def test_main(self):\n        self.assertIsNone(main())\n\nif __name__ == '__main__':\n    unittest.main()"
     )
     test_dir.add(py_test_file)
     self.root.add(py_file, test_dir)
Beispiel #2
0
 def create(self) -> NoReturn:
     """
     Create the structure of the project.
     """
     self.verify_installation()
     self.root = Folder(self.path)
     readme = ReadMeFile(self.path)
     readme.write_title(self.name)
     readme.write_paragraph(
         "Project generated with `project_automation` module")
     readme.write_from_dict(self.CONFIG['readme_content'])
     gitignore = GitIgnoreFile(self.path, self.CONFIG['languages'])
     self.root.add(readme, gitignore)
     if self.github_settings != {}:
         if self.user is None:
             raise PermissionError(
                 "you must put your credentials into .env file to create repository"
             )
         self.user.create_repo(self.name,
                               private=not self.github_settings['public'])
         license_file = LicenseFile(self.path,
                                    self.github_settings['license'],
                                    self.user.name)
         self.root.add(license_file)
    def create(self) -> NoReturn:
        """
        Create the structure of the project.

        See also
        --------
        utils.execute_command2
        """
        sass = 'y' in input(
            "Do you want to include Sass/Scss files ? (y/n) ").lower()
        ts = 'y' in input(
            "Do you want to include TypeScript files ? (y/n) ").lower()
        super().create()
        os.chdir(self.path)
        source_folder_path = os.path.join(self.path, "src")
        source_folder = Folder(source_folder_path)
        self.root.add(Folder(os.path.join(self.path, "public")), source_folder)
        if self.allow_install:
            execute_command2(
                'npm i -D webpack webpack-cli webpack-dev-server @babel/core babel-loader @babel/preset-env html-webpack-plugin html-loader file-loader style-loader css-loader mini-css-extract-plugin')
            package_json = read_from_json_file(
                os.path.join(self.path, 'package.json'))
            package_json['scripts'] = {
                "build": "webpack --mode=production",
                "start": "webpack-dev-server"
            }
            write_in_json_file(os.path.join(
                self.path, 'package.json'), package_json, indent_json=2)
            if sass:
                execute_command2("npm i -D node-sass sass-loader webpack-sass")
            if ts:
                execute_command2("npm i -D ts-loader typescript")
                execute_command2('tsc --init')
                print("Finally, change target by \"es6\" and module by \"es2015\"")
        else:
            print('Launch this command `npm i -D webpack webpack-cli webpack-dev-server @babel/core babel-loader @babel/preset-env`')
            print("Change the 'scripts' part of the package.json file :")
            print("- build value : webpack --mode=production")
            print("- start value : webpack-dev-server")
            print("Execute the following commands :")
            print("\tnpm i -D html-webpack-plugin html-loader file-loader")
            print("\tnpm i -D style-loader css-loader mini-css-extract-plugin")
            if sass:
                print("\tnpm i -D node-sass sass-loader webpack-sass")
            if ts:
                print("\tnpm i -D ts-loader typescript")
                print("\ntsc --init")
                print("Finally, change target by \"es6\" and module by \"es2015\"")
        ts_content = """{
        test: /\.tsx?$/,
        include: [path.resolve(__dirname, "src")],
        use: "ts-loader",
        exclude: /node_modules/,
      },"""
        ts_resolve = """".tsx", ".ts","""
        sass_content = """{
        test: /\.scss$/,
        include: [path.resolve(__dirname, "src")],
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
      },"""
        webpack_config_content = f"""const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {{
  mode: "development", // development or production
  devtool: "eval-source-map",
  entry: "./src/app.js",
  module: {{
    rules: [
      {{
        test: /\.jsx?$/,
        exclude: /node_modules/,
        include: [path.resolve(__dirname, "src")],
        use: "babel-loader",
      }},
      {ts_content if ts else ''}
      {{
        test: /\.css$/,
        include: [path.resolve(__dirname, "src")],
        use: [
          MiniCssExtractPlugin.loader,
          "css-loader",
        ],
      }},
      {sass_content if sass else ''}
      {{
        test: /\.html$/,
        include: [path.resolve(__dirname, "src")],
        use: [
          {{
            loader: "html-loader",
            options: {{ minimize: true }},
          }},
        ],
      }},
      {{
        test: /\.(png|svg|jpg|jpeg|gif)$/,
        include: [path.resolve(__dirname, "src")],
        use: "file-loader",
      }},
    ],
  }},
  resolve: {{ extensions: [{ts_resolve if ts else ''}".jsx", ".js"] }},
  plugins: [
    new HtmlWebpackPlugin({{
      filename: "index.html",
      template: "src/index.html",
    }}),
    new MiniCssExtractPlugin({{
      filename: "index.css",
    }}),
  ],
  output: {{
    filename: "app.bundle.js",
    path: path.resolve(__dirname, "public"),
  }},
}};
"""
        webpack_config = JavascriptFile(self.path, 'webpack.config')
        webpack_config.write(webpack_config_content)
        self.root.add(webpack_config)

        assets_dir = Folder(os.path.join(source_folder_path, "assets"))
        images_dir = Folder(os.path.join(
            os.path.join(source_folder_path, "assets"), "images"))
        fonts_dir = Folder(os.path.join(
            os.path.join(source_folder_path, "assets"), "fonts"))
        assets_dir.add(images_dir, fonts_dir)
        source_folder.add(assets_dir)

        css_dir = Folder(os.path.join(source_folder_path, "styles"))
        if sass:
            style = SASSFile(os.path.join(
                source_folder_path, "styles"), "main")
        else:
            style = CSSFile(os.path.join(
                source_folder_path, "styles"), "style")
        css_dir.add(style)
        source_folder.add(css_dir)

        if ts:
            main_ts = TypescriptFile(source_folder_path, 'main')
            main_ts.write("export const perfect: string = \"perfect\";\n")
            source_folder.add(main_ts)
        app_js = JavascriptFile(source_folder_path, 'app')
        app_js.write(f"""{"import './styles/main.scss';" if sass else "import './styles/style.css';"}
import {{ bro }} from "./bro";
{"import { perfect } from './main';" if ts else ''}

let ok = ["ok", "ok"];
console.log(ok);
console.log(bro("Dude"));
{"console.log(perfect);" if ts else ''}
""")
        bro_js = JavascriptFile(source_folder_path, 'bro')
        bro_js.write("""export const bro = (greeting) => {
  return `${greeting}, bro`;
};
""")
        source_folder.add(bro_js, app_js, HTMLFile(
            source_folder_path, 'index'))
Beispiel #4
0
    def create(self) -> NoReturn:
        """
        Create the structure of the project.
        """
        super().create()
        # Create the JS folder and JS files
        js_dir = Folder(os.path.join(self.path, "js"))
        script = TypescriptFile(os.path.join(self.path, "js"), "script")
        js_dir.add(script)

        # Create the CSS folder and CSS files
        css_dir = Folder(os.path.join(self.path, "style"))
        style = CSSFile(os.path.join(self.path, "style"), "style")
        css_dir.add(style)

        # Create other folders
        assets_dir = Folder(os.path.join(self.path, "assets"))
        images_dir = Folder(
            os.path.join(os.path.join(self.path, "assets"), "images"))
        fonts_dir = Folder(
            os.path.join(os.path.join(self.path, "assets"), "fonts"))
        assets_dir.add(images_dir, fonts_dir)

        # Create some files
        index_html_file = HTMLFile(self.path, "index")
        index_html_file.add_headlink(type="text/css",
                                     rel="stylesheet",
                                     href=style.filename,
                                     href_is_relative=False)
        index_html_file.add_script(src=script.filename, src_is_relative=False)
        self.root.add(index_html_file, js_dir, css_dir, assets_dir)
Beispiel #5
0
    def create(self) -> NoReturn:
        """
        Create the structure of the project.
        """
        super().create()
        composer_json_file = JSONFile(self.path, 'composer')
        composer_json_file.write({
            "name": "pds/skeleton",
            "type": "standard",
            "description": "Standard for PHP package skeletons.",
            "homepage": "https://github.com/php-pds/skeleton",
            "license": "CC-BY-SA-4.0",
            "autoload": {
                "psr-4": {
                    "Pds\\Skeleton\\": "src/"
                }
            },
            "autoload-dev": {
                "psr-4": {
                    "Pds\\Skeleton\\": "tests/"
                }
            },
            "bin": ["bin/pds-skeleton"]
        })
        self.root.add(composer_json_file)

        bin_dir = Folder(os.path.join(self.path, "bin"))
        config_dir = Folder(os.path.join(self.path, "config"))
        docs_dir = Folder(os.path.join(self.path, "docs"))
        public_dir = Folder(os.path.join(self.path, "public"))
        src_dir = Folder(os.path.join(self.path, "src"))
        ressources_dir = Folder(os.path.join(self.path, "ressources"))
        src_dir = Folder(os.path.join(self.path, "src"))
        tests_dir = Folder(os.path.join(self.path, "tests"))
        vendor_dir = Folder(os.path.join(self.path, "vendor"))
        self.root.add(bin_dir, config_dir, docs_dir, public_dir,
                      src_dir, ressources_dir, tests_dir, vendor_dir)

        # Create the JS folder and JS files
        js_dir = Folder(os.path.join(self.path, "src", "js"))
        script = JavascriptFile(os.path.join(self.path, "src", "js"), "script")
        js_dir.add(script)

        # Create the CSS folder and CSS files
        css_dir = Folder(os.path.join(self.path, "src", "style"))
        style = CSSFile(os.path.join(self.path, "src", "style"), "style")
        css_dir.add(style)

        # Create other folders
        assets_dir = Folder(os.path.join(self.path, "src", "assets"))
        images_dir = Folder(os.path.join(self.path, "src", "assets", "images"))
        fonts_dir = Folder(os.path.join(self.path, "src", "assets", "fonts"))
        assets_dir.add(images_dir, fonts_dir)

        # Create some files
        index_html_file = HTMLFile(os.path.join(self.path, "src"), "index")
        index_html_file.add_headlink(
            type="text/css", rel="stylesheet", href=style.filename, href_is_relative=False)
        index_html_file.add_script(src=script.filename, src_is_relative=False)
        index_html_file.write_xml()
        php_file = PHPFile(os.path.join(self.path, "src"), "index")
        # Transfert the HTML content to PHP file
        content = index_html_file.read()
        start_H1 = content.find("<h1>")
        end_H1 = content.find("</h1>")
        # Change the H1 tag
        content2 = content[:start_H1 + len("<h1>")] + \
            "<?php echo \"Hello World\"; ?>" + content[end_H1:]
        php_file.write(content2)
        # Delete the HTML file
        index_html_file.remove()
        src_dir.add(php_file, js_dir, css_dir, assets_dir)
Beispiel #6
0
class Project:
    """
    Represents a simple project to create.

    Attributes
    ----------
    path : str
        path of the parent root of the project
    name : str
        name of the project (used for make directory and github repo)
    allow_install : bool
        True if you want to automatically install the required packages, False otherwise
    github_settings : dict
        some github informations
    errors : list of string
        all occured error during project creation (not exceptions)
    user : ~github.AuthenticatedUser or ~github.NamedUser
        github user if ``github_settings`` is not empty
    root : ~files.Folder
        root folder of the project
    """

    CONFIG = {'languages': [], 'readme_content': {}}

    def __init__(self,
                 path: str,
                 name: str,
                 allow_install: bool,
                 github_settings: dict = {},
                 **kwargs: Any) -> NoReturn:
        """
        Constructor and initializer.

        Parameters
        ----------
        path : str
            path of the parent root of the project
        name : str
            name of the project (used for make directory and github repo)
        allow_install : bool
            True if you want to automatically install the required packages, False otherwise
        github_settings : dict
            some github informations
        **kwargs : Any
            other keywords parameters
        """
        self.errors = []
        try:
            client = None
            if GITHUB_OAUTH_ACCESS_TOKEN is not None:
                client = github.Github(GITHUB_OAUTH_ACCESS_TOKEN)
            else:
                client = github.Github(GITHUB_USER, GITHUB_PASS)
            self.user = client.get_user()
        except github.BadCredentialsException:
            self.errors.append("Your Github credentials are bad.")
            self.user = None
        except github.TwoFactorException:
            self.errors.append(
                "You have activate the 2-Factor-Authentication on Github. Use the OAuth access token to bypass the 2FA (developer tab)."
            )
            self.user = None
        self.path = os.path.join(path, name)
        self.name = name
        self.github_settings = github_settings
        self.allow_install = allow_install

    def create(self) -> NoReturn:
        """
        Create the structure of the project.
        """
        self.verify_installation()
        self.root = Folder(self.path)
        readme = ReadMeFile(self.path)
        readme.write_title(self.name)
        readme.write_paragraph(
            "Project generated with `project_automation` module")
        readme.write_from_dict(self.CONFIG['readme_content'])
        gitignore = GitIgnoreFile(self.path, self.CONFIG['languages'])
        self.root.add(readme, gitignore)
        if self.github_settings != {}:
            if self.user is None:
                raise PermissionError(
                    "you must put your credentials into .env file to create repository"
                )
            self.user.create_repo(self.name,
                                  private=not self.github_settings['public'])
            license_file = LicenseFile(self.path,
                                       self.github_settings['license'],
                                       self.user.name)
            self.root.add(license_file)

    def verify_installation(self) -> NoReturn:
        """
        Verify if all the required programs are installed.

        See also
        --------
        utils.execute_command
        """
        if self.github_settings != {} and self.user is not None:
            GitCommand(self.allow_install)

    def commit(self, message="Initial commit") -> NoReturn:
        """
        Commit all the project to the Github repo (if ``github_settings`` attribute is not empty)
        and show all the errors occured in the execution.

        Parameters
        ----------
        message : str
            commit message into the repo

        See also
        --------
        utils.execute_command
        """
        os.chdir(self.path)
        execute_command2(f"cd {self.path}")
        if self.github_settings != {} and self.user is not None:
            execute_command2("git init")
            execute_command2(f"git add {self.path}")
            execute_command2(f"git commit -m \"{message}\"")
            execute_command2(
                f"git remote add origin https://github.com/{self.user.login}/{self.name}.git"
            )
            execute_command2("git push -u origin master")
        elif self.user is None:
            self.errors.append(
                "You cannot push your modification on your repo.")

        error_len = len(self.errors)
        print(
            f"There are {SHELL_COLORS['green'] if error_len == 0 else SHELL_COLORS['red']}{error_len}{SHELL_COLORS['endcolor']} errors arrived during the execution (not exceptions){'' if error_len == 0 else ' :'}"
        )
        for error in self.errors:
            print(f"- {error}")
        self.errors = []

    def structure(self) -> NoReturn:
        """
        Show the structure of the project.

        See also
        --------
        utils.tree
        """
        tree(self.path)

    def remove_project(self) -> NoReturn:
        """
        Remove the whole project.
        """
        self.root.remove_folder()
Beispiel #7
0
    def create(self) -> NoReturn:
        """
        Create the structure of the project.
        """
        super().create()
        if self.generate_files:
            if self.executing_scripts:
                name = self.company_name
                if self.company_name == 'nobody' and self.user is not None:
                    name = self.user.name
                manifest_file = TextFile(self.path, 'Manifest')
                manifest_file.write(
                    f"Main-Class: {self.package_name}.Main\nManifest-Version: 1.0\nCreated-By: {name}"
                )

                compile_script_content = f"javac -encoding \"utf-8\" -d build/ src/{self.package_name}/*.java"
                compile_bash_script = BashFile(self.path, 'compile')
                compile_bash_script.write(compile_script_content)
                compile_batch_script = BatchFile(self.path, 'compile')
                compile_batch_script.write(compile_script_content)
                self.root.add(compile_bash_script, compile_batch_script)

                install_script_content = f"if [ ! -d lib ]; then lib ( mkdir lib )fi\nif [ ! -e lib/junit-platform-console-standalone-1.6.2.jar ]; then cd lib\nwget https://repo1.maven.org/maven2/org/junit/platform/junit-platform-console-standalone/1.6.2/junit-platform-console-standalone-1.6.2.jar"
                install_script_content2 = f"if not exist lib ( mkdir lib )\nif not exist lib\junit-platform-console-standalone-1.6.2.jar (cd lib\npowershell.exe -command \"Invoke-WebRequest https://repo1.maven.org/maven2/org/junit/platform/junit-platform-console-standalone/1.6.2/junit-platform-console-standalone-1.6.2.jar -o junit-platform-console-standalone-1.6.2.jar\")"
                install_bash_script = BashFile(self.path, 'install')
                install_bash_script.write(install_script_content)
                install_batch_script = BatchFile(self.path, 'install')
                install_batch_script.write(install_script_content2)
                self.root.add(install_bash_script, install_batch_script)

                if sys.platform == 'win32':
                    run_script_content = "call compile.bat"
                else:
                    run_script_content = "sh compile.sh"
                run_script_content += f"\njava -cp build {self.package_name}.Main"
                run_bash_script = BashFile(self.path, 'run')
                run_bash_script.write(run_script_content)
                run_batch_script = BatchFile(self.path, 'run')
                run_batch_script.write(run_script_content)
                self.root.add(run_bash_script, run_batch_script)

                doc_script_content = f"javadoc -encoding \"utf-8\" -docencoding \"utf-8\" -d doc/ src/{self.package_name}/*.java "
                doc_bash_script = BashFile(self.path, 'doc')
                doc_bash_script.write(doc_script_content)
                doc_batch_script = BatchFile(self.path, 'doc')
                doc_batch_script.write(doc_script_content)
                self.root.add(doc_bash_script, doc_batch_script)

                if sys.platform == 'win32':
                    package_script_content = "call compile.bat"
                else:
                    package_script_content = "sh compile.sh"
                package_script_content += f"\ncd build/\njar cfm {self.package_name}.jar \"../Manifest.txt\" {self.package_name}/\ncd ..\nmkdir dist\n"
                if sys.platform == 'win32':
                    package_script_content += f"move \"build\{self.package_name}.jar\" dist/"
                else:
                    package_script_content += f"mv build/{self.package_name}.jar dist/{self.package_name}.jar"
                package_bash_script = BashFile(self.path, 'package')
                package_bash_script.write(package_script_content)
                package_batch_script = BatchFile(self.path, 'package')
                package_batch_script.write(package_script_content)
                self.root.add(package_bash_script, package_batch_script)

            package_path = os.path.join(self.path, 'src', self.package_name)
            package_dir = Folder(package_path)
            java_file = JavaFile(package_path, "Main", self.package_name)

            package_info_file = JavaFile(package_path, "package-info",
                                         self.package_name)
            package_info_file.write(f"""/**
* <b>Description : </b> Packages organisation for the project.
* 
* @author {self.company_name}
* 
* @version 0.1
*/""")
            package_dir.add(java_file, package_info_file)
            self.root.add(package_dir)