개발 기록

Hugo 블로그 생성 과정 기록 (with Docsy theme)

ch-yang 2022. 12. 22. 13:04

Hugo 설치

참고 : https://010000.github.io/post/20191214_install_hugo_windows/

  1. golang 설치
    • https://go.dev/dl/
    • Microsoft Windows 설치 (1.19.4)
    • 시스템 환경 변수 Path에 “C:\Program Files\Go\bin” 경로가 자동 등록되었다.
    • go version 명령어로 설치 확인
  2. Git 은 이미 설치되어 있음.
  3. Hugo 설치
    • 공식 설치 가이드
    • https://gohugo.io/installation/windows/
    • Hugo Editions가 Standard, Extended가 있는데 Extended Edition 설치를 추천
    • Chocolatey 아니면 Scoop 를 설치하라고 그러네? 뭐지?
    • → Windows용 패키지 매니저란다.

Chocolatey

  • Chocolatey?
    • Windows용 패키지 매니저
    • MS가 공식으로 제공하는 도구는 아니다.
  • 공식 설치 가이드
  • https://chocolatey.org/install
  • PowerShell 에서 다음 명령을 수행
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
 
 
  • 설치되어 있다. 언제 설치했는지 모르겠다… 버전 업데이트나 해주자
  • 관리자 권한이 필요하다네. 관리자 권한으로 다시 열어서 진행
  • choco upgrade chocolatey
  • → chocolatey v1.2.1 으로 업그레이드

  • choco를 사용해서 hugo extended edition을 설치하자
#설치
choco install hugo-extended

#Hugo 설치 확인 (버전 및 환경 변수 확인)
hugo env
hugo version
 
 

설치 완료!

새 Hugo site 생성

  • Document : https://gohugo.io/getting-started/quick-start/#explanation-of-commands
  • 이 다음부터는 PowerShell 이 아닌 cmder 를 사용해서 진행했다. (개인 취향)
  • 명령어를 수행한 Directory 아래 지정한 이름으로(hugo-blog) 폴더가 생성됐다.
  •  1C:\2.Project\2.github-blog
     2λ hugo new -h
     3Create a new content file and automatically set the date and title.
     4It will guess which kind of file to create based on the path provided.
     5
     6You can also specify the kind with `-k KIND`.
     7
     8If archetypes are provided in your theme or site, they will be used.
     9
    10Ensure you run this within the root directory of your site.
    11
    12Usage:
    13  hugo new [path] [flags]
    14  hugo new [command]
    15
    16Available Commands:
    17  site        Create a new site (skeleton)
    18  theme       Create a new theme
    19
    20C:\2.Project\2.github-blog
    21λ hugo new site hugo-blog
    22Congratulations! Your new Hugo site is created in C:\2.Project\2.github-blog\hugo-blog.
    23
    24Just a few more steps and you're ready to go:
    25
    261. Download a theme into the same-named folder.
    27   Choose a theme from https://themes.gohugo.io/ or
    28   create your own with the "hugo new theme <THEMENAME>" command.
    292. Perhaps you want to add some content. You can add single files
    30   with "hugo new <SECTIONNAME>\<FILENAME>.<FORMAT>".
    313. Start the built-in live server via "hugo server".
    32
    33Visit https://gohugo.io/ for quickstart guide and full documentation.
    
     

테마 선택 (Docsy)

Docsy Theme Build - 1. Use Docsy as a Hugo Module

https://www.docsy.dev/docs/get-started/docsy-as-module/

Docsy의 두가지 Build Option

두 옵션 모두 모든 종속성을 설치하기 위해 prerequisites 가이드를 따라야 한다.

이번에는 Clone 하고 끝내는 초보자용이 아닌 숙련자용 가이드로 진행한다

  • Copy and edit the source for the Docsy example site. This approach gives you a skeleton structure for your site, with top-level and documentation sections and templates that you can modify as necessary. The example site uses Docsy as a Hugo Module.
  • → 초보자용 가이드 : Start with a prepopulated site
  • Build your own site using the Docsy theme. Specify the Docsy theme like any other Hugo theme when creating or updating your site. With this option, you’ll get Docsy look and feel, navigation, and other features, but you’ll need to specify your own site structure.
  • → 숙련자용 가이드 : Start a site from scratch

Create a new site : Start a new site from scratch (숙련자용)

hugo new site my-new-site
cd  my-new-site
hugo mod init github.com/me/my-new-site
hugo mod get github.com/google/docsy@0.6.0
hugo mod get github.com/google/docsy/dependencies@0.6.0
(echo [module]^

[[module.imports]]^

path = "github.com/google/docsy"^

[[module.imports]]^

path = "github.com/google/docsy/dependencies")>>config.toml
hugo server
  • @0.6.0 는 Docsy 프로젝트의 Release 버전이다.
  • 아래 내용이 config.toml 에 추가 된다.
[module]
proxy = "direct"
[[module.imports]]
path = "github.com/google/docsy"
[[module.imports]]
path = "github.com/google/docsy/dependencies"
 

[로컬 서버 실행]→ 아무것도 없는 빈 사이트가 실행된다.

Docsy Theme Build - 2. Docsy as a Git submodule

https://www.docsy.dev/docs/get-started/other-options/

  • Hugo Module 방식이 아닌 Git Submodule 방식은 구식이라고 한다.
  • 다른 Hugo Theme들이 이 방식을 사용하는 것 같아 따라해본다.
  • → 다른 Theme의 예제들을 참고하기에도 이 방법이 좋을 것 같다.

Git submodule 이란?

  • Document : https://git-scm.com/book/ko/v2/Git-도구-서브모듈
    프로젝트를 수행하다 보면 다른 프로젝트를 함께 사용해야 하는 경우가 종종 있다. 함께 사용할 다른 프로젝트는 외부에서 개발한 라이브러리라던가 내부 여러 프로젝트에서 공통으로 사용할 라이브러리일 수 있다. 이런 상황에서 자주 생기는 이슈는 두 프로젝트를 서로 별개로 다루면서도 그 중 하나를 다른 하나 안에서 사용할 수 있어야 한다는 것이다.
    
    Atom 피드를 제공하는 웹사이트를 만드는 것을 예로 들어보자. Atom 피드를 생성하는 코드는 직접 작성하지 않고 라이브러리를 가져다 쓰기로 한다. 라이브러리를 사용하려면 CPAN이나 Ruby gem 같은 라이브러리 관리 도구를 사용하여 Shared 라이브러리 형태로 쓰거나 직접 라이브러리의 소스코드를 프로젝트로 복사해서 사용할 수 있다. 우선 Shared 라이브러리를 사용하기에는 문제가 있다. 프로젝트를 사용하는 모든 환경에 라이브러리가 설치되어 있어야 하고 라이브러리를 프로젝트에 맞게 약간 수정해서 사용하고 배포하기가 어렵다. 또한, 라이브러리 소스코드를 직접 프로젝트에 포함시키는 경우에는 라이브러리 Upstream 코드가 업데이트됐을 때 Merge 하기가 어렵다.
    
    Git의 서브모듈은 이런 문제를 다루는 도구다. Git 저장소 안에 다른 Git 저장소를 디렉토리로 분리해 넣는 것이 서브모듈이다. 다른 독립된 Git 저장소를 Clone 해서 내 Git 저장소 안에 포함할 수 있으며 각 저장소의 커밋은 독립적으로 관리한다.

Node: Get the latest LTS release (노드 버전 최신화)

  • Node 버전 최신화가 안되어 있으면 build error 가 발생한다.
C:\2.Project\2.github-blog
λ cd yblog\

C:\2.Project\2.github-blog\yblog
λ git init

C:\2.Project\2.github-blog\yblog (master)
λ git submodule add https://github.com/google/docsy.git themes/docsy
Cloning into 'C:/2.Project/2.github-blog/yblog/themes/docsy'...
remote: Enumerating objects: 9084, done.
remote: Counting objects: 100% (185/185), done.
remote: Compressing objects: 100% (104/104), done.
remote: Total 9084 (delta 103), reused 123 (delta 68), pack-reused 8899R
Resolving deltas: 100% (5644/5644), done. MiB | 7.62 MiB/s, done.
warning: LF will be replaced by CRLF in .gitmodules.
The file will have its original line endings in your working directory

C:\2.Project\2.github-blog\yblog (master)
λ hugo server
Start building sites …
hugo v0.108.0-a0d64a46e36dd2f503bfd5ba1a5807b900df231d+extended windows/amd64 BuildDate=2022-12-06T13:37:56Z VendorInfo=gohugoio
ERROR 2022/12/13 19:38:54 render of "home" failed: "C:\2.Project\2.github-blog\yblog\themes\docsy\layouts\_default\baseof.html:16:7": execute of template failed: template: home.html:16:7: executing "home.html" at <partialCached "scripts.html" .>: error calling partialCached: "C:\2.Project\2.github-blog\yblog\themes\docsy\layouts\partials\scripts.html:82:30": execute of template failed: template: partials/scripts.html:82:30: executing "partials/scripts.html" at <resources.Concat>: error calling Concat: slice []interface {} not supported in concat
ERROR 2022/12/13 19:38:54 render of "taxonomy" failed: "C:\2.Project\2.github-blog\yblog\themes\docsy\layouts\_default\baseof.html:16:7": execute of template failed: template: _default/terms.html:16:7: executing "_default/terms.html" at <partialCached "scripts.html" .>: error calling partialCached: "C:\2.Project\2.github-blog\yblog\themes\docsy\layouts\partials\scripts.html:82:30": execute of template failed: template: partials/scripts.html:82:30: executing "partials/scripts.html" at <resources.Concat>: error calling Concat: slice []interface {} not supported in concat
ERROR 2022/12/13 19:38:54 failed to render pages: render of "taxonomy" failed: "C:\2.Project\2.github-blog\yblog\themes\docsy\layouts\_default\baseof.html:16:7": execute of template failed: template: _default/terms.html:16:7: executing "_default/terms.html" at <partialCached "scripts.html" .>: error calling partialCached: "C:\2.Project\2.github-blog\yblog\themes\docsy\layouts\partials\scripts.html:82:30": execute of template failed: template: partials/scripts.html:82:30: executing "partials/scripts.html" at <resources.Concat>: error calling Concat: slice []interface {} not supported in concat
Error: Error building site: TOCSS: failed to transform "scss/main.scss" (text/x-scss): "C:\2.Project\2.github-blog\yblog\themes\docsy\assets\scss\main.scss:6:1": File to import not found or unreadable: ../vendor/bootstrap/scss/bootstrap.
Built in 38 ms
  • 나는 Chocolatey가 설치되어 있으니 choco 명령어를 사용해서 Node 버전을 업그레이드 했다.
     
#버전 확인
node -v

#nodejs-lts 업그레이드
choco upgrade nodejs-lts

#공식 문서에서는 아래 명령을 사용했다.
nvm install --lts

submodule 추가 (테마 추가)

cd hugo-blog
git init

git submodule add --depth 1 https://github.com/google/docsy.git themes/docsy
 

config.toml 수정

#windows가 문제인지 아래 명령을 수행하면 작은 따옴표까지 삽입된다.
echo 'theme = "docsy"' >> config.toml

#그냥 config.toml 을 에디터로 열고 아래에 내용을 직접 삽입해줬다.
theme = "docsy"
 

Docsy 종속성 설치

cd themes/docsy
npm install

Install PostCSS

  • 프로젝트 root에서 수행한다.
  • “node_modules”아래 모듈이 설치된다. (package.json도 생성된다.)
npm install --save-dev autoprefixer postcss-cli postcss
 
 

(편의. Optional) npm scripts 수정

  • 프로젝트 root에 있는 “package.json”에 아래 노란색 내용을 추가한다.
  • 프로젝트 root에서 “npm install”을 수행하면 docsy가 최신버전으로 업데이트 된다.
{
  "devDependencies": {
    "autoprefixer": "^10.4.13",
    "postcss": "^8.4.20",
    "postcss-cli": "^10.1.0"
  },
  "scripts": {
    "get:submodule": "git submodule update --init --depth 1",
    "_prepare:docsy": "cd themes/docsy && npm install",
    "prepare": "npm run get:submodule && npm run _prepare:docsy"
  }
}

Local Server 실행

hugo server

1/public
2resources/
3node_modules/
4package-lock.json
5.hugo_build.lock
 
 
  • 이후 부터는 2. Docsy as a Git submodule 방식으로 진행)

Basic Site Configuration

  • 아래 example 의 config.toml 을 Copy 하는 것을 추천한다.
  • theme = "docsy” 는 없길래 따로 세번째 줄에 추가했다.
    • docsy-example 은 hugo module을 방식이여서 theme, baseURL 설정이 안되어 있다.
  • config.toml 아래 쪽에 있는 hugo module 설정 부분은 제외
  • 최종 Basic config.toml
    baseURL = "/"
    title = "Goldydocs"
    theme = "docsy"
    
    # Language settings
    contentDir = "content/en"
    defaultContentLanguage = "en"
    defaultContentLanguageInSubdir = false
    # Useful when translating.
    enableMissingTranslationPlaceholders = true
    
    enableRobotsTXT = true
    
    # Will give values to .Lastmod etc.
    enableGitInfo = true
    
    # Comment out to enable taxonomies in Docsy
    # disableKinds = ["taxonomy", "taxonomyTerm"]
    
    # You can add your own taxonomies
    [taxonomies]
    tag = "tags"
    category = "categories"
    
    [params.taxonomy]
    # set taxonomyCloud = [] to hide taxonomy clouds
    taxonomyCloud = ["tags", "categories"] 
    
    # If used, must have same length as taxonomyCloud
    taxonomyCloudTitle = ["Tag Cloud", "Categories"] 
    
    # set taxonomyPageHeader = [] to hide taxonomies on the page headers
    taxonomyPageHeader = ["tags", "categories"] 
    
    # Highlighting config
    pygmentsCodeFences = true
    pygmentsUseClasses = false
    # Use the new Chroma Go highlighter in Hugo.
    pygmentsUseClassic = false
    #pygmentsOptions = "linenos=table"
    # See https://help.farbox.com/pygments.html
    pygmentsStyle = "tango"
    
    # Configure how URLs look like per section.
    [permalinks]
    blog = "/:section/:year/:month/:day/:slug/"
    
    # Image processing configuration.
    [imaging]
    resampleFilter = "CatmullRom"
    quality = 75
    anchor = "smart"
    
    [services]
    [services.googleAnalytics]
    # Comment out the next line to disable GA tracking. Also disables the feature described in [params.ui.feedback].
    id = "UA-00000000-0"
    
    # Language configuration
    
    [languages]
    [languages.en]
    title = "Goldydocs"
    description = "A Docsy example site"
    languageName ="English"
    # Weight used for sorting.
    weight = 1
    [languages.no]
    title = "Goldydocs"
    description = "Docsy er operativsystem for skyen"
    languageName ="Norsk"
    contentDir = "content/no"
    time_format_default = "02.01.2006"
    time_format_blog = "02.01.2006"
    
    [languages.fa]
    title = "اسناد گلدی"
    description = "یک نمونه برای پوسته داکسی"
    languageName ="فارسی"
    contentDir = "content/fa"
    time_format_default = "2006.01.02"
    time_format_blog = "2006.01.02"
    
    [markup]
      [markup.goldmark]
        [markup.goldmark.renderer]
          unsafe = true
      [markup.highlight]
        # See a complete list of available styles at https://xyproto.github.io/splash/docs/all.html
        style = "tango"
        # Uncomment if you want your chosen highlight style used for code blocks without a specified language
        # guessSyntax = "true"
    
    # Everything below this are Site Params
    
    # Comment out if you don't want the "print entire section" link enabled.
    [outputs]
    section = ["HTML", "print", "RSS"]
    
    [params]
    copyright = "The Docsy Authors"
    privacy_policy = "https://policies.google.com/privacy"
    
    # First one is picked as the Twitter card image if not set on page.
    # images = ["images/project-illustration.png"]
    
    # Menu title if your navbar has a versions selector to access old versions of your site.
    # This menu appears only if you have at least one [params.versions] set.
    version_menu = "Releases"
    
    # Flag used in the "version-banner" partial to decide whether to display a 
    # banner on every page indicating that this is an archived version of the docs.
    # Set this flag to "true" if you want to display the banner.
    archived_version = false
    
    # The version number for the version of the docs represented in this doc set.
    # Used in the "version-banner" partial to display a version number for the 
    # current doc set.
    version = "0.0"
    
    # A link to latest version of the docs. Used in the "version-banner" partial to
    # point people to the main doc site.
    url_latest_version = "https://example.com"
    
    # Repository configuration (URLs for in-page links to opening issues and suggesting changes)
    github_repo = "https://github.com/google/docsy-example"
    # An optional link to a related project repo. For example, the sibling repository where your product code lives.
    github_project_repo = "https://github.com/google/docsy"
    
    # Specify a value here if your content directory is not in your repo's root directory
    # github_subdir = ""
    
    # Uncomment this if your GitHub repo does not have "main" as the default branch,
    # or specify a new value if you want to reference another branch in your GitHub links
    github_branch= "master"
    
    # Google Custom Search Engine ID. Remove or comment out to disable search.
    gcs_engine_id = "d72aa9b2712488cc3"
    
    # Enable Algolia DocSearch
    algolia_docsearch = false
    
    # Enable Lunr.js offline search
    offlineSearch = false
    
    # Enable syntax highlighting and copy buttons on code blocks with Prism
    prism_syntax_highlighting = false
    
    # User interface configuration
    [params.ui]
    #  Set to true to disable breadcrumb navigation.
    breadcrumb_disable = false
    # Set to true to disable the About link in the site footer
    footer_about_disable = false
    # Set to false if you don't want to display a logo (/assets/icons/logo.svg) in the top navbar
    navbar_logo = true
    # Set to true if you don't want the top navbar to be translucent when over a `block/cover`, like on the homepage.
    navbar_translucent_over_cover_disable = false
    # Enable to show the side bar menu in its compact state.
    sidebar_menu_compact = false
    # Set to true to hide the sidebar search box (the top nav search box will still be displayed if search is enabled)
    sidebar_search_disable = false
    
    # Adds a H2 section titled "Feedback" to the bottom of each doc. The responses are sent to Google Analytics as events.
    # This feature depends on [services.googleAnalytics] and will be disabled if "services.googleAnalytics.id" is not set.
    # If you want this feature, but occasionally need to remove the "Feedback" section from a single page,
    # add "hide_feedback: true" to the page's front matter.
    [params.ui.feedback]
    enable = true
    # The responses that the user sees after clicking "yes" (the page was helpful) or "no" (the page was not helpful).
    yes = 'Glad to hear it! Please tell us how we can improve.'
    no = 'Sorry to hear that. Please tell us how we can improve.'
    
    # Adds a reading time to the top of each doc.
    # If you want this feature, but occasionally need to remove the Reading time from a single page, 
    # add "hide_readingtime: true" to the page's front matter
    [params.ui.readingtime]
    enable = false
    
    [params.links]
    # End user relevant links. These will show up on left side of footer and in the community page if you have one.
    [[params.links.user]]
      name = "User mailing list"
      url = "https://example.org/mail"
      icon = "fa fa-envelope"
      desc = "Discussion and help from your fellow users"
    [[params.links.user]]
      name ="Twitter"
      url = "https://example.org/twitter"
      icon = "fab fa-twitter"
      desc = "Follow us on Twitter to get the latest news!"
    [[params.links.user]]
      name = "Stack Overflow"
      url = "https://example.org/stack"
      icon = "fab fa-stack-overflow"
      desc = "Practical questions and curated answers"
    # Developer relevant links. These will show up on right side of footer and in the community page if you have one.
    [[params.links.developer]]
      name = "GitHub"
      url = "https://github.com/google/docsy"
      icon = "fab fa-github"
      desc = "Development takes place here!"
    [[params.links.developer]]
      name = "Slack"
      url = "https://example.org/slack"
      icon = "fab fa-slack"
      desc = "Chat with other project developers"
    [[params.links.developer]]
      name = "Developer mailing list"
      url = "https://example.org/mail"
      icon = "fa fa-envelope"
      desc = "Discuss development issues around the project"
    
    # hugo module configuration
    #  - It was excluded because it uses "Git submodule".
    #[module]
      # uncomment line below for temporary local development of module
      # replacements = "github.com/google/docsy -> ../../docsy"
    #  [module.hugoVersion]
    #    extended = true
    #    min = "0.75.0"
    #  [[module.imports]]
    #    path = "github.com/google/docsy"
    #    disable = false
    #  [[module.imports]]
    #    path = "github.com/google/docsy/dependencies"
    #    disable = false

Publish Site (Github)

Github 레포지토리 생성

  1. Build Project Repository : {any}
  2. publish site Repository : {username}.github.io
[Example]
//1
hugo-blog
//2
ch-yang1273.github.io
 

Git repository 연결

  • Hugo site build 프로젝트 Repository 연결
# git remote add origin http://github.com/{username}/{any}.git
git remote add origin http://github.com/ch-yang1273/hugo-blog.git
  • Build 된 Site Repository 연결
  • Build 된 Site는 public 폴더에 생성된다. 
# git submodule add -b master https://github.com/{username}/{username}.github.io.git public
git submodule add -b master https://github.com/ch-yang1273/ch-yang1273.github.io.git public

 

config.toml 의 baseURL 수정

  • 접속할 URL로 수정
# baseURL = "https://{username}.github.io/"
baseURL = "https://ch-yang1273.github.io/"

Build Site

  • publish 할 site 가 public 폴더에 생성된다.
    # hugo 나 hugo -t docsy 모두 똑같이 빌드되었다.
    hugo -t docsy

Github에 Build Project 와 Publish Site 를 push

  • public 폴더 먼저 commit해야 한다.
    C:\2.Project\2.github-blog\hugo-blog\public (master -> origin)
    λ git add .
    
    C:\2.Project\2.github-blog\hugo-blog\public (master -> origin)
    λ git commit -m "first"
    
    C:\2.Project\2.github-blog\hugo-blog\public (master -> origin)
    λ git push
  • build project 부터 진행하면 git add . 부터 실패한다.
  • 그 다음으로 Build Project 를 push
  • C:\2.Project\2.github-blog\hugo-blog (master)
    λ git add .
    
    C:\2.Project\2.github-blog\hugo-blog (master)
    λ git commit -m "first"
    
    C:\2.Project\2.github-blog\hugo-blog (master)
    λ git push

Publish 완료

  • 브라우저에서 https://{username}.github.io/
  • https://ch-yang1273.github.io/
     
  • 결과 이미지4

업로드 자동화

#!/bin/bash

# Build the project.
hugo -t <테마이름>

# github.io 레포 push위해 파일 경로 이동
cd public
# 충돌 방지를 위해 한번 pull
git pull origin master

# git내용들 추가
git add .

# Commit 바꾸기. git commit -m "원하는 커밋 메세지"를 입력하거나
# git commit만 입력시 커밋날짜를 메세지로 자동설정
msg="rebuilding site `date`"
if [ $# -eq 1 ]
  then msg="$1"
fi
git commit -m "$msg"

# github.io 레포에 push
git push origin master

# 상위 폴더인 blog도 push위해 경로 변경
cd ..

# blog 저장소 Commit & Push
# 충돌 방지를 위해 한번 pull
git pull origin master
git add .

msg="rebuilding site `date`"
if [ $# -eq 1 ]
  then msg="$1"
fi
git commit -m "$msg"

git push origin master

'개발 기록' 카테고리의 다른 글

yum  (0) 2023.04.11
MySQL/MariaDB 쿼리 기록  (0) 2023.04.11
Docker Ubuntu-mySQL 서버 생성 기록  (0) 2023.01.26
Windows에서 WSL2를 활용한 Docker 사용 관련 기록  (0) 2023.01.20